const HOUR_S = 3600;
const HOUR_MS = 3600000;
const DAY_MS = 1000*HOUR_S*24;
function get_time_zone()
{
    return new Date().getTimezoneOffset()*60*-1;
}
function convert_time(date)
{
    return date+get_time_zone();
}
function convert_time_ms(date,type)
{
    if(!type) return date+get_time_zone()*1000;
    return date;
}

function cloneObject(obj)
{
    var newobj = new Object();
    for (var key in obj)
    {
        newobj[key]=obj[key];
    }
    return newobj;
}
function cloneArr(arr)
{
    var newarr = [];
    for (var i = 0; i<arr.length; i++)
    {
        newarr[i]=arr[i];
    }
    return newarr;
}
function isObject(obj)
{
    return typeof obj === 'object' && obj !== null;
}

class vega_converter
{
    constructor()
    {
    }
    get_time_zone()
    {
        return new Date().getTimezoneOffset()*60*-1;
    }
    timeInUtc(s)
    {
        return s - this.get_time_zone();
    }
    intToHex(number,countByte)
    {
        var result = '';
        try
        {
            if (number<0)
            {
                var maxValue = '';
                while((maxValue.length/2)<countByte)
                {
                    maxValue+='ff';
                }
                maxValue='0x'+maxValue;
                result = this.uIntToHex(Number(maxValue)+number+1);
                while((result.length/2)<countByte)
                {
                    result+='00';
                }
                return result;
            }
            else
            {
                result = this.uIntToHex(number);
                while((result.length/2)<countByte)
                {
                    result+='00';
                }
                return result;
            }
        }
        catch (e)
        {
            console.log(e);
        }
        return result;
    }
    uIntToHex(number,countByte)
    {
        try
        {
            if (typeof number === 'string' ) 
            {
                number = parseInt(number);
            }
            if (typeof number === 'number'&&!isNaN(number)&&number>=0&&number%1 === 0)
            {
                var hex = number.toString(16);
                while(hex.length%2!==0)
                {
                    hex='0'+hex;
                }
                var bytes = this.hexToBytes(hex);
                bytes.reverse();
                hex = bytes.join('');
                if( countByte !== undefined )
                {
                    while( (hex.length/2) < countByte )
                    {
                        hex+='00';
                    }
                }
                return hex;
            }
        }
        catch (e)
        {
            console.log(e);
        }
        return '';
    }
    intToBytes(number,count)
    {
        if (count!==undefined)
        {
            var hex = '';
            if (number!==undefined)
            {
                number = parseInt(number);
                if (!isNaN(number))
                {
                    hex = number.toString(16);
                }
            }
            var hex_array = [];
            var beginNulls = (count*2) - hex.length;
            while(beginNulls>0)
            {
                hex='0'+hex;
                beginNulls--;
            }
            for (var i =0;i<count*2;i+=2)
            {
                if (hex[i]!==undefined&&hex[i+1]!==undefined)
                {
                    hex_array.push( hex.substring(i, i+2) ); 
                }
                else if (hex[i]!==undefined&&hex[i].length===1)
                {
                    var byte = "0"+hex[i];
                    hex_array.push( byte ); 
                }
                else
                {
                    hex_array.unshift('00' );
                }
            }
            hex_array.reverse();
            return hex_array.join('' );
        }
        else
        {
            return '0';
        }
    }
    parse0_21mB(value,min,max)
    {
        value = value/1000;
        return (min+(((max-min)*(value))/21));
    }
    parse4_20mA(value,min,max)
    {
        return min+(((max-min)*(value-4))/16);
    }
    to4_20mA(value,min,max)
    {
        return  ( ( ( ( value - min ) * 16 ) / ( max - min ) ) + 4 ) ; 
    }
    round_size(num,decimal)
    {
        if (decimal==undefined||decimal<=0)
        {
            decimal = 1;
        }
        var decimal = Math.pow(10,decimal);
        return(Math.round(num*decimal)/decimal);
    }
    round_size_str(num,decimal)
    {
        var r = this.round_size(num,decimal);
        var str = r.toString();
        var arr = str.split('.' );
        var tmp = arr[1];
        if (tmp===undefined)
        {
            tmp = '';
        }
        while(tmp.length<decimal)
        {
            tmp+='0';
        }
        return arr[0]+'.'+tmp;
    }
    hexToBytes(hex)
    {
        var bytes = [];
        for (var i = 0; i < hex.length - 1; i = i+2)
        {
           bytes.push( hex.substring(i, i+2) ); 
        }
        return bytes;
    }
    bytesToParamsSettings(bytes)
    {
        var result = new Object();
        bytes.splice(0,1);
        while(bytes.length>0)
        {
            var sizeParam = this.bytesToUint( [bytes[2]]);
            var idParamHex = this.bytesToUint( [bytes[0],bytes[1]]);
            if (isNaN(sizeParam)||isNaN(idParamHex)||idParamHex===undefined)
            {
                break;
            }
            else
            {
                bytes.splice(0,3);
            }
            var paramBytes = [];
            for(var i = 0; i<sizeParam; i++)
            {
                var paramByte = bytes[i];
                if (paramByte!==undefined)
                {
                    paramBytes.push(paramByte);
                }
                else
                {
                    break;
                }
            }
            bytes.splice(0,sizeParam);
            result[idParamHex] = 
            {
                id:idParamHex,
                size:sizeParam,
                rawData:paramBytes
            }
        }
        return result;
    }
    bytesAsciiToString(bytes,begin,end)
    {
        var chars = [];
        try 
        {
            for ( var i = 0; i<bytes.length; i++ )
            {
                if(i<begin) continue;
                if(i>=end) break;
                var byte = bytes[i];
                var code_char = `0x${byte}`;
                var char = String.fromCharCode(code_char);
                chars.push(char);
            }
        } 
        catch (error) 
        {
            
        }
        finally
        {
            return chars.join('');
        }
    }
    bytesToInt(bytes)
    {
        try
        {
            var valid_arr = isObject(bytes) && bytes.length;
            if (valid_arr)
            {
                // var countMAX = 0;
                bytes.reverse();
                var result='';
                for(var i = 0; i<bytes.length;i++)
                {
                    // if (bytes[i]=='ff' ) countMAX++;
                    result+=bytes[i]===undefined?'00':bytes[i].toString();
                }
                var resultNumber = undefined;
                // if (countMAX==bytes.length)
                // {
                //     resultNumber = undefined;
                // }
                // else
                // {
                    resultNumber = parseInt(result,16);
                    var maxVal = Math.pow(2, result.length / 2 * 8);
                    if (!isNaN(resultNumber))
                    {
                        if (resultNumber > maxVal / 2 - 1) 
                        {
                            resultNumber = resultNumber - maxVal;
                        }
                    }
                // }
                return resultNumber;
            }
            else
            {
                return NaN;
            }
        }
        catch(e)
        {
            console.log(e);
            return NaN;
        }
    }
    bytesToUint(bytes)
    {
        try
        {
            var valid_arr = isObject(bytes) && bytes.length;
            if (valid_arr)
            {
                // var countMAX = 0;
                bytes.reverse();
                var result='';
                for(var i = 0; i<bytes.length;i++)
                {
                    // if (bytes[i]=='ff' ) countMAX++;
                    result+=bytes[i]===undefined?'00':bytes[i].toString();
                }
                var resultNumber = undefined;
                // if (countMAX==bytes.length)
                // {
                //     resultNumber = undefined;
                // }
                // else
                // {
                    resultNumber = parseInt(result,16);
                // }
                return resultNumber;
            }
            else
            {
                return NaN;
            }
        }
        catch(e)
        {
            console.log(e);
            return NaN;
        }
    }
    decodeAes(data,key)
    {
        var res = {
            status:false
        };
        var validAesjs = typeof aesjs === 'object';
        var validData = typeof data === 'string';
        var validKey = typeof key === 'string';
        if ( !validAesjs || !validData || !validKey ) return res;
        try
        {
            var keyBytes = aesjs.utils.hex.toBytes(key);
            var dataBytes = aesjs.utils.hex.toBytes(data);
            var myAes = new aesjs.AES(keyBytes);
            var decryptData = myAes.decrypt(dataBytes);
            res.status = true;
            res.data = aesjs.utils.hex.fromBytes(decryptData);
        }
        catch(e)
        {
            res.status = false;
            delete res.data;
        }
        finally
        {
            return res;
        }
    }
}
class VegaReport extends vega_converter 
{
    constructor(types)
    {
        super();
        this.sort = 'level_2';
        this.status = false;
        this.types = types;
        this.loader = false;
        this.queueWaiting = new Object();
        this.queueSuccess = new Object();
        this.totalCount = 0;
        this.date_range = new date_range();
        this.reload();
    }
    resetProgress()
    {
        this.status = false;
        this.loader = false;
        this.queueWaiting = new Object();
        this.queueSuccess = new Object();
        this.totalCount = 0;
    }
    set progress(val)
    {
        this._progress = val;
    }
    get firstChannel()
    {
        for(var key in this.queueWaiting)
        {
            return this.queueWaiting[key];
        }
        return new Object();
    }
    get cCount()
    {
        return Object.keys(this.queueWaiting).length;
    }
    get progress()
    {
        if (this.totalCount<=0)
        {
            return 100;
        }
        else 
        {
            var progress = 100-Math.round((100*this.cCount)/this.totalCount);
            return progress>100||isNaN(progress)?100:progress;
        }
    }
    backPage()
    {
        switch (this.step) {

            case 2:
                this.step--;
                this.selectedType = undefined;
                break;
            case 3:
                this.step--;
                this.selectedObject = undefined;
                break;
            case 4:
                this.step--;
                break;
            default:
                break;
        }
    }
    nextPage()
    {
        if (!this.checkDisabled())
        {
            this.step++;
        }
    }
    reload()
    {
        this.step = 1;
        this.selectedTypeChannel = undefined;
        this.selectedType = undefined;
        this.selectedObject = undefined;
        this.sort = 'level_2';
    }
    generation()
    {
        $('#reportProgress' ).modal('hide' );
        this.loader = false;
        this.report = new Object();
        this.report.channels = [];
        this.report.sum = 0;
        var filterPackage = undefined;
        if (this.selectedType.id==5&&this.selectedTypeChannel.id==14)
        {
            filterPackage=4;
        }
        for(var key in this.queueSuccess) 
        {
            var channel = this.queueSuccess[key];
            var info = channel.getInfo(this.date_range,filterPackage);
            this.report.channels.push(info);
            this.report.sum = this.report.sum+info.consum_sum;
            this.report.sum_rate_1 = this.report.sum_rate_1+info.consum_1;
            this.report.sum_rate_2 = this.report.sum_rate_2+info.consum_2;
            this.report.sum_rate_3 = this.report.sum_rate_3+info.consum_3;
            this.report.sum_rate_4 = this.report.sum_rate_4+info.consum_4;
        }
        this.report.sum= this.round_size(this.report.sum,4);
        this.status = true;
        this.report.info = new Object();
        this.report.info.nameFile = this.selectedType.name+'-'+this.selectedObject.name+', c '+moment.unix(this.date_range.getStart()).format('DD.MM.YY' )+' по '+moment.unix(this.date_range.getEnd()).format('DD.MM.YY' );
        switch (this.selectedType.id) {
            case 1:
                if (this.selectedTypeChannel.id==1||this.selectedTypeChannel.id==14||this.selectedTypeChannel.id==16)
                {
                    this.report.info.countCol = 11;
                }
                else
                {
                    this.report.info.countCol=10;
                }
                break;
            case 2:
                if (this.selectedTypeChannel.id==1||this.selectedTypeChannel.id==14||this.selectedTypeChannel.id==16)
                {
                    this.report.info.countCol = 8;
                }
                else if ( this.selectedTypeChannel.id==23 || this.selectedTypeChannel.id==25 )
                {
                    this.report.info.countCol = 6;
                }
                else
                {
                    this.report.info.countCol=7;
                }
                break;
            case 5:
                if (this.selectedTypeChannel.id==14||this.selectedTypeChannel.id==16)
                {
                    this.report.info.countCol = 11;
                }
                else
                {
                    this.report.info.countCol=10;
                }
                break;
            default:
                this.report.info.countCol=10;
                break;
        }
        this.report.dangers = function()
        {
            var dangers = [];
            for(var i = 0; i<this.channels.length;i++)
            {
                var channel = this.channels[i];
                for(var key in channel.dangers)
                {
                    var danger = channel.dangers[key];
                    danger.level_2 = channel.level_2;
                    danger.name = channel.name;
                    danger.desc = channel.desc;
                    dangers.push(danger);
                }
            }
            return dangers;
        }
        
    }
    startFormingReport()
    {
        this.resetProgress();
        this.queueWaiting = this.getChannels();
        this.queueSuccess = new Object();
        this.status = false;
        this.totalCount = Object.keys(this.queueWaiting).length;
        this.loader = true;
    }
    getChannels()
    {
        try 
        {
            return this.selectedObject.getChannels('type_channel',this.selectedTypeChannel.id);
        } 
        catch (e) 
        {
            return new Object();
        }
    }
    checkDisabled()
    {
        switch (this.step) 
        {
            case 1:
                if (this.selectedTypeChannel)
                {
                    return false;
                }
                break;
            case 2:
                if (this.selectedType)
                {
                    return false;
                }
                break;
            case 3:
                if (this.selectedObject)
                {
                    return false;
                }
                break;
            case 4:
                    return false;
                break;
            default:
                break;
        }
        return true;
    }
    getText()
    {
        switch (this.step) {
            case 1:
                    return "Выберите тип устройств для которых Вы собираетесь выполнить запрос формирования отчета";
                break;
            case 2:
                    return "Выберите вид отчета, который вы собираетесь сформировать";
                break;
            case 3:
                    return "Выберите объект";
                break;
            default:
                    return "";
                break;
        }
    }
}
class command_list
 {
     constructor()
    {
       this.get_users=false;
       this.manage_users=false;
       this.delete_users=false;
       this.get_device_appdata=false;
       this.get_data=false;
       this.send_data=false;
       this.manage_device_appdata=false;
       this.delete_device_appdata=false;
       this.get_gateways=false;
       this.manage_gateways=false;
       this.delete_gateways=false;
       this.get_devices=false;
       this.manage_devices=false;
       this.delete_devices=false;
       this.get_coverage_map=false;
       this.get_device_downlink_queue=false;
       this.manage_device_downlink_queue=false;
    }
    selectAll()
    {
        var valid = new valid_data();
        for (var key in this)
        {
            if (valid.isBool(this[key]))
            {
                this[key]=true;
            }
        }
    }
    unselectAll()
    {
        var valid = new valid_data();
        for (var key in this)
        {
            if (valid.isBool(this[key]))
            {
                this[key]=false;
            }
        }
    }
    set_patterns(pattern)
    {
        var valid = new valid_data();
        for (var key in pattern)
        {
            if (pattern[key]!=undefined&&valid.isBool(pattern[key])&&this[key]!=undefined&&valid.isBool(this[key]))
            {
                this[key]=pattern[key];
            }
        }
    }
    set_command_list_array(c_list)
    {
        var valid = new valid_data();
        if (c_list!==undefined&&c_list.length>0)
        {
            for (var i = 0 ; i<c_list.length;i++)
            {
                if (this[c_list[i]]!==undefined&&valid.isBool(this[c_list[i]]))
                {
                    this[c_list[i]]=true;
                }
            }  
        }
    }
    get_command_list_array()
    {
        var valid = new valid_data();
        var temp_array = new Array();
        for (var key in this)
        {
            if (valid.isBool(this[key]))
            {
                temp_array.push(key);
            }
        }
        return temp_array;
    }
 }
class sticky
{
    constructor()
    {
        this.general_info = true;
        this.summary_info = true;
        this.chart_consum = false;
        this.chart_consum_new = false;
        this.chart_consum1 = false;
        this.chart_consum2 = false;
        this.chart_consum4 = false;
        this.chart_temperature = false;
        this.chart_conn = false;
        this.danger=false;
        this.chart_consum_danger=false;
        this.data = false;
        this.data_event = false;
        this.data_energy = false;
        this.data_energy_archive = false;
        this.data_slices = false;
        this.data_journals = false;
        this.data_history = false;
        this.data_instant = false;
        this.data_instant2 = false;
        this.data_info = false;
        this.data_info2 = false;
        this.data_jp = false;
        this.data_rl = false;
        this.menu=true;
        this.map=true;
    }
    toogle(str)
    {
        this[str]=this[str]?false:true;
    }
}

class report_consum
{
    constructor()
    {
        this.level_1 = new Array();
        this.level_2 = new Array();
        this.type_channel = [''];
        this.device = [];
        this.channel = [];
        this.date_range = new date_range();
        this.interval;
        this.good_devices = new Array();
    }
    check_all_channel_report()
    {
        for (var i=0;i<this.channel.length;i++)
        {
            this.channel[i].tick=true;
        }
    }
    none_all_channel_report()
    {
        for (var i=0;i<this.channel.length;i++)
        {
            this.channel[i].tick=false;
        }
    }
    get()
    {
        return this.channel;
    }
    search_device()
    {
    }
}
class valid_data 
{
    constructor()
    {
        
    }
    valid(str)
    {
        if (str!==undefined&&str.toString().length>0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    name(str)
    {
        if (this.valid(str)&&str.length<=25)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    comment(str)
    {
        if (this.valid(str)&&str.length<=200)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    address(str)
    {
        if (this.valid(str))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    isSMS(str)
    {
         if (this.valid(str)&&str.length<=70)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    isMessenger(str)
    {
         if (this.valid(str)&&str.length<=1000)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    isInt(str)
    {
        if (this.isNumber(str)&&str % 1 === 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    devEui(str)
    {
        return (this.valid(str)&&str.length===16);
    }
    isNumber(str)
    {
        if (str!==undefined&&!isNaN(str)&&str!=="")
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    isBool(str)
    {
        if (typeof str==="boolean")
        {
            return true;
        }
        else return false;
    }
    isDate(str)
    {
        if (str!==undefined)
        {
            try
            {
                var date = Math.abs(new Date(str).getTime());
                if (date>0&&this.isInt(date))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch(err)
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
}
class edit_device
{
    constructor(type)
    {
        this.device = new device();
        this.level_1 = new Object();
        this.level_2;
        this.num_channel;
        this.status;
        this.color = new Object();
        this.info_channel;
        this.init_value;
        this.kt;
        this.name;
        this.type_channel = new Object();
        this.division;
        this.history;
        this.calib_interval;
        this.ia;
        this.model;
        this.serial;
        this.personal_num;
        this.type_meter = 0;
        this.title = 'Создание нового устройства';
        this._init_status=false;
        this.type=type;
        this.security_name;
        this.hall_1_name;
        this.hall_2_name;
        this.water;
        this.rason;
        this.min_t=-55;
        this.max_t=100;
        this.vega_valid =  new valid_data();
        
       
        this.instrument;
        this.instrument2;
        this.unit;
        this.min_v;
        this.max_v;
        this.min_normal_v;
        this.max_normal_v;
        this.security_name_2;
        this.sensor_name_1;
        this.sensor_name_2;

        this.temperature_sensor_name_1 = 'Температура 1';
        this.temperature_sensor_name_2 = 'Температура 2';
        this.temperature_sensor_name_3 = 'Температура 3';
        this.temperature_sensor_name_4 = 'Температура 4';
        this.temperature_sensor_name_5 = 'Температура 5';
        this.temperature_sensor_name_6 = 'Температура 6';
        this.temperature_sensor_name_7 = 'Температура 7';
        this.temperature_sensor_name_8 = 'Температура 8';
        this.temperature_sensor_name_9 = 'Температура 9';
        this.temperature_sensor_name_10 = 'Температура 10';
        
        this.provider;
        this.typeCargo = '1';
        this.cargo;
        
        this.name_sensor_in_1;
        this.name_sensor_in_2;
        this.name_sensor_out_1;
        this.name_sensor_out_2;
        
        
        this.state_sensor_0;
        this.state_sensor_1;
        this.telephones='';
        this.emails='';
        this.telegram_chats = '';
        this.message_sms = '';
        this.message_messenger = '';
        this.sms=false;
        this.email=false;
        this.telegram=false;
        this.enable_danger = false;
        this.user_message_danger = true;
        this.app_message_danger = false;
        this.voice = false;
        this.voice_message = '';
        this.count_rate;
        this.count_phase = 1;
        this.display_power_profile = true;
        this.relay = false;

        this.last_date = new Date(moment().format('YYYY-MM-DD' ));
        this.date_installation = new Date(moment().format('YYYY-MM-DD' ));
        this.date_shipment = new Date(moment().format('YYYY-MM-DD' ));
        this.valid_user_message_danger
    }
    /**
     * 
     * @returns true/false возвращает правильная или не правильное сообщение о тревожном
     * событии
     * 
     */
    valid_user_message_danger()
    {
        return this.vega_valid.isBool(this.user_message_danger);
    }
    valid_app_message_danger()
    {
        return this.vega_valid.isBool(this.app_message_danger);
    }
    valid_enable_danger()
    {
        return this.vega_valid.isBool(this.enable_danger);
    }
    valid_sms()
    {
        return this.vega_valid.isBool(this.sms);
    }
    valid_email()
    {
        return this.vega_valid.isBool(this.email);
    }
    valid_telegram()
    {
        return this.vega_valid.isBool(this.telegram);
    }
    valid_voice()
    {
        return this.vega_valid.isBool(this.voice);
    }
    valid_message_sms()
    {
        return this.vega_valid.isSMS(this.message_sms);
    }
    valid_message_messenger()
    {
        return this.vega_valid.isMessenger(this.message_messenger);
    }
    valid_voice_message()
    {
        return this.vega_valid.comment(this.voice_message);
    }
    valid_telephones()
    {
        return true;
    }
    valid_emails()
    {
        return true;
    }
    valid_telegram_chats()
    {
        return true;
    }
    valid_kt()
    {
        return this.vega_valid.isNumber(this.kt);
    }
    valid_count_rate()
    {
        return this.vega_valid.isInt(this.count_rate)&&this.count_rate>=1&&this.count_rate<=4;
    }
    valid_count_phase()
    {
        return this.vega_valid.isInt(this.count_phase)&&(this.count_phase===1||this.count_phase===3);
    }
    valid_display_power_profile()
    {
        return this.vega_valid.isBool(this.display_power_profile);
    }
    valid_relay()
    {
        return this.vega_valid.isBool(this.relay);
    }
    valid_instrument()
    {
        return this.vega_valid.name(this.instrument);
    }
    valid_instrument2()
    {
        return this.vega_valid.name(this.instrument2);
    }

    valid_temperature_sensor_name(i)
    {
        return this.vega_valid.name(this[`temperature_sensor_name_${i}`]);
    }
    

    valid_sensor_name_2()
    {
        return this.vega_valid.name(this.sensor_name_2);
    }
    valid_name_sensor_in_1()
    {
        return this.vega_valid.name(this.name_sensor_in_1);
    }
    valid_name_sensor_in_2()
    {
        return this.vega_valid.name(this.name_sensor_in_2);
    }
    valid_name_sensor_out_1()
    {
        return this.vega_valid.name(this.name_sensor_out_1);
    }
    valid_name_sensor_out_2()
    {
        return this.vega_valid.name(this.name_sensor_out_2);
    }
    
    
    valid_sensor_name_1()
    {
        return this.vega_valid.name(this.sensor_name_1);
    }
    valid_security_name_2()
    {
        return this.vega_valid.name(this.security_name_2);
        
    }
    valid_typeCargo()
    {
        return this.typeCargo?true:false;
    }
    valid_provider()
    {
        return this.vega_valid.name(this.provider);
    }
    valid_cargo()
    {
        return this.vega_valid.name(this.cargo);
    }
    
    valid_max_normal_v()
    {
         return this.vega_valid.isNumber(this.max_normal_v);
    }
    valid_min_normal_v()
    {
         return this.vega_valid.isNumber(this.min_normal_v);
    }
    valid_range_normal_value()
    {
        if(this.version == 1)
        {
            return this.valid_max_v()&&this.valid_min_v();
        }
        else 
        {
            if (this.valid_max_normal_v()&&this.valid_min_normal_v()&&this.valid_max_v()&&this.valid_min_v())
            {
                var min = parseFloat(this.min_v);
                var max = parseFloat(this.max_v);
                var min_n = parseFloat(this.min_normal_v);
                var max_n = parseFloat(this.max_normal_v);
                if (max_n>min_n&&max>=max_n&&min<=min_n)
                {
                    return true;
                }
            }
            return false;
        }
    }
    valid_range_value2()
    {
        if (this.valid_max_v()&&this.valid_min_v())
        {
            return true;
        }
        return false;
    }
    valid_range_value()
    {
        if (this.valid_max_v()&&this.valid_min_v())
        {
            var min = parseFloat(this.min_v);
            var max = parseFloat(this.max_v);
            if (max>min)
            {
                return true;
            }
        }
        return false;
    }
    valid_max_v()
    {
         return this.vega_valid.isNumber(this.max_v);
    }
    valid_min_v()
    {
         return this.vega_valid.isNumber(this.min_v);
    }
    valid_unit()
    {
        return this.vega_valid.name(this.unit);
    }
    valid_devEui()
    {
        return this.vega_valid.devEui(this.device.devEui);
    }
    valid_personal_num()
    {
        return this.vega_valid.name(this.personal_num);
    }
    valid_comment()
    {
        return this.vega_valid.comment(this.info_channel)
    }
    valid_type_channel()
    {
        return this.type_channel&&this.vega_valid.isInt(this.type_channel.id);
    }
    valid_division()
    {
        return this.vega_valid.isNumber(this.division);
    }
    valid_init_value()
    {
        return this.vega_valid.isNumber(this.init_value);
    }
    valid_last_date()
    {
        return this.vega_valid.isDate(this.last_date)
    }
    valid_name_level_1()
    {
        return this.vega_valid.name(this.level_1.name_level_1);
    }
    
    valid_security_name()
    {
        return this.vega_valid.name(this.security_name);
    }
    valid_hall_1_name()
    {
        return this.vega_valid.name(this.hall_1_name);
    }
    valid_hall_2_name()
    {
        return this.vega_valid.name(this.hall_2_name);
    }
    valid_water()
    {
       return this.water==1||this.water==2?true:false;
    }
    valid_name()
    {
        return this.vega_valid.name(this.name)
    }
    valid_name_level_2()
    {
        return this.vega_valid.name(this.level_2);
    }
    valid_address_level_1()
    {
        return this.vega_valid.address(this.level_1.address_level_1);
    }
    valid_num_channel()
    {
        return this.vega_valid.isInt(this.num_channel);
    }
    valid_status()
    {
        return this.vega_valid.isInt(this.status);
    }
    valid_color()
    {
        return this.vega_valid.isInt(this.color.id);
    }
    valid_ia()
    {
        var isInt = this.vega_valid.isInt(this.ia);
        if(this.type_meter == 5) return isInt || !this.ia;
        return isInt;
    }
    valid_mac()
    {
        return this.mac;
    }
    valid_key()
    {
        return this.key;
    }
    valid_calib_interval()
    {
        return this.vega_valid.isInt(this.calib_interval);
    }
    valid_1()
    {
        if (this.type_channel.type==1)
        {
             try
            {
                this.init_value = this.init_value.replace(/,/,'.' );
                this.division = this.division.replace(/,/,'.' );
                if (this.type_channel.id==1) 
                {
                    this.kt = this.kt.toString().replace(/,/,'.' );
                }
                else
                {
                    this.kt=1;
                }
            }
            catch(err)
            {
                return false;
            }
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_division())
            {
                return false;
            }
            if (!this.valid_init_value())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_calib_interval())
            {
                return false;
            }
            return true;
        }
        else if (this.type_channel.type==2)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_4()
    {
        if (this.type_channel.type==3)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            if (!this.valid_security_name())
            {
                return false;
            }
            if (!this.valid_hall_1_name())
            {
                return false;
            }
            if (!this.valid_hall_2_name())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_td11rev2()
    {
        if (this.type_channel.type==3)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            if (!this.valid_security_name())
            {
                return false;
            }
            if (!this.valid_hall_1_name())
            {
                return false;
            }
            if (!this.valid_hall_2_name())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
     valid_6()
    {
        if (this.type_channel.type==6&&this.valid_smart())
        {   
            if (!this.valid_instrument())
            {
                return false;
            } 
            if( this.version == 1 )
            {
                if (!this.valid_instrument2())
                {
                    return false;
                } 
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_smart()
    {
        if (this.type_channel.type==6)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            } 
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_tl11()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }   
        if (!this.valid_provider())
        {
            return false;
        }
        if (!this.valid_cargo())
        {
            return false;
        }
        if (!this.valid_typeCargo())
        {
            return false;
        }
        if (!this.valid_personal_num())
        {
            return false;
        }
        return true;
    }

    valid_td12()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }   
        if (!this.valid_provider())
        {
            return false;
        }
        if (!this.valid_cargo())
        {
            return false;
        }
        if (!this.valid_hall_1_name())
        {
            return false;
        }
        if (!this.valid_typeCargo())
        {
            return false;
        }
        if (!this.valid_personal_num())
        {
            return false;
        }
        return true;
    }
    valid_5()
    {
        if (this.type_channel.type==5)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }    
            if (!this.valid_instrument())
            {
                return false;
            }
            if (!this.valid_sensor_name_2())
            {
                return false;
            }
            if (!this.valid_sensor_name_1())
            {
                return false;
            }
            if (!this.valid_security_name_2())
            {
                return false;
            }
            if (!this.valid_security_name())
            {
                return false;
            } 
            if (!this.valid_range_normal_value())
            {
                return false;
            }
            if (!this.valid_range_value())
            {
                return false;
            }
            if (!this.valid_unit())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    basicValid()
    {
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        
        return true;
    }
    valid_sh02()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        if (this.type_channel.type==29)
        {
            if (!this.valid_instrument())
            {
                return false;
            }
            if (!this.valid_range_value2())
            {
                return false;
            }
            if (!this.valid_unit())
            {
                return false;
            }
        }
        if (this.type_channel.type==28)
        {
            for(var i = 1; i<=10; i++)
            {
                if (!this.valid_temperature_sensor_name(i))
                {
                    return false;
                }
            }
        }
        if (this.type_channel.type==1)
        {
            try
            {
                this.init_value = this.init_value.replace(/,/,'.' );
                this.division = this.division.replace(/,/,'.' );
                if (this.type_channel.id==1) 
                {
                    this.kt = this.kt.toString().replace(/,/,'.' );
                }
                else
                {
                    this.kt=1;
                }
            }
            catch(err)
            {
                return false;
            }
            
            if (!this.valid_division())
            {
                return false;
            }
            if (!this.valid_init_value())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
           
            if (!this.valid_num_channel())
            {
                return false;
            }
            
            if (!this.valid_calib_interval())
            {
                return false;
            }
            return true;
        }
        else if (this.type_channel.type==2)
        {
            return true;
        }
        else if (this.type_channel.type==22)
        {
            if (!this.valid_ia())
            {
                return false;
            }
            return true;
        }
        else if (this.type_channel.type==28)
        {
            return true;
        }
        else if (this.type_channel.type==29)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_si13_merc()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        if (this.type_channel.type==9)
        {
            if (!this.valid_count_phase())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
            if (!this.valid_calib_interval())
            {
                return false;
            }
            if (!this.valid_ia())
            {
                return false;
            }
            if (!this.valid_kt()) 
            {
                return false;
            }
            return true;
        }
        else if (this.type_channel.type==1)
        {
            try
            {
                this.init_value = this.init_value.replace(/,/,'.' );
                this.division = this.division.replace(/,/,'.' );
                if (this.type_channel.id==1) 
                {
                    this.kt = this.kt.toString().replace(/,/,'.' );
                }
                else
                {
                    this.kt=1;
                }
            }
            catch(err)
            {
                return false;
            }
            
            if (!this.valid_division())
            {
                return false;
            }
            if (!this.valid_init_value())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
           
            if (!this.valid_num_channel())
            {
                return false;
            }
            
            if (!this.valid_calib_interval())
            {
                return false;
            }
            return true;
        }
        else if (this.type_channel.type==2)
        {
            return true;
        }
        else if (this.type_channel.type==22)
        {
            if (!this.valid_ia())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_ue()
    {
        if (this.type_channel.type==7)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            if (!this.valid_count_rate())
            {
                return false;
            }
            if (!this.valid_count_phase())
            {
                return false;
            }
            if (!this.valid_display_power_profile())
            {
                return false;
            }
            if (!this.valid_relay())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
            if (!this.valid_calib_interval())
            {
                return false;
            }
            if (this.type_meter == 5)
            {

            }
            else if (!this.valid_ia())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_ue2()
    {
        if (this.type_channel.type==7)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            if (!this.valid_count_rate())
            {
                return false;
            }
            if (!this.valid_count_phase())
            {
                return false;
            }
            if (!this.valid_display_power_profile())
            {
                return false;
            }
            if (!this.valid_relay())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
            if (!this.valid_calib_interval())
            {
                return false;
            }
            if (!this.valid_ia())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_ug()
    {
        if (this.type_channel.type==8)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            
            if (!this.valid_name_sensor_in_1())
            {
                return false;
            }
            if (!this.valid_name_sensor_in_2())
            {
                return false;
            }
            if (!this.valid_name_sensor_out_1())
            {
                return false;
            }
            if (!this.valid_name_sensor_out_2())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
            if (!this.valid_calib_interval())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_gm_1()
    {
        if (this.type_channel.type==8)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
            if (!this.valid_calib_interval())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_lm1()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        if (!this.valid_security_name())
        {
            return false;
        }
        return true;
    }
    valid_src()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        return true;
    }
    valid_9()
    {
        if (this.type_channel.type==4)
        {
            if (!this.valid_devEui())
            {
                return false;
            }
            if (!this.valid_comment())
            {
                return false;
            }
            if (!this.valid_type_channel())
            {
                return false;
            }
            if (!this.valid_name_level_1())
            {
                return false;
            } 
            if (!this.valid_name())
            {
                return false;
            }
            if (!this.valid_name_level_2())
            {
                return false;
            }
            if (!this.valid_address_level_1())
            {
                return false;
            }
            if (!this.valid_num_channel())
            {
                return false;
            }
            if (!this.valid_color())
            {
                return false;
            }
            if (!this.valid_status())
            {
                return false;
            }
            if (!this.valid_water())
            {
                return false;
            }
            if (!this.valid_last_date())
            {
                return false;
            }
            if (!this.valid_calib_interval())
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    valid_hs()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        if (!this.valid_security_name_2())
        {
            return false;
        }
        if (!this.valid_security_name())
        {
            return false;
        } 
        return true;
    }
    valid_um()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        
        return true;
    }
    valid_mbus()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        if ( this.type_channel.type == 20 )
        {
            if (!this.valid_last_date())
            {
                return false;
            }
            if (!this.valid_calib_interval())
            {
                return false;
            }
            if (!this.valid_ia())
            {
                return false;
            }
        }
        else if( this.type_channel.type != 2 )
        {
            return false;
        }
        return true;
    }
    valid_therm()
    {
        if (!this.valid_devEui())
        {
            return false;
        }
        if (!this.valid_comment())
        {
            return false;
        }
        if (!this.valid_type_channel())
        {
            return false;
        }
        if (!this.valid_name_level_1())
        {
            return false;
        } 
        if (!this.valid_name())
        {
            return false;
        }
        if (!this.valid_name_level_2())
        {
            return false;
        }
        if (!this.valid_address_level_1())
        {
            return false;
        }
        if (!this.valid_num_channel())
        {
            return false;
        }
        if (!this.valid_color())
        {
            return false;
        }
        if (!this.valid_status())
        {
            return false;
        }
        if (!this.valid_mac())
        {
            return false;
        }
        if (!this.valid_key())
        {
            return false;
        }
        return true;
    }
    valid()
    {
        var dt = parseInt(this.device.device_type);
        switch (dt) {
            case 1:
                return this.valid_1();
                break;
            case 2:
                return this.valid_1();
                break;
            case 3:
                return this.valid_si13_merc();
                break;
            case 4:
                if ( this.version == 1 )
                {
                    return this.valid_td11rev2();
                }
                else if ( this.version == 0 )
                {
                    return this.valid_4();
                }
                else
                {
                    return false;
                }
                break;
            case 5:
                return this.valid_5();
                break;  
            case 6:
                return this.valid_6();
                break;
            case 7:
                return this.valid_smart();
                break;
            case 8:
                return this.valid_smart();
                break;
            case 9:
                return this.valid_9();
                break;
            case 10:
                return this.valid_smart();
                break;
            case 11:
                return this.valid_1();
                break;
            case 12:
                return this.valid_ue();
                break;
            case 13:
                return this.valid_ug();
                break;
            case 14:
                return this.valid_lm1();
                break;
            case 15:
                if ( this.version == 1 )
                {
                    return this.valid_tl11();
                }
                else if ( this.version == 0 )
                {
                    return this.valid_td12();
                }
                else
                {
                    return false;
                }
                
                break;  
            case 17:
                return this.valid_gm_1();
                break;
            case 18:
                return this.valid_1();
                break;
            case 20:
                return this.valid_mbus();
                break;
            case 21:
                return this.valid_mbus();
                break;
            case 23:
                return this.valid_hs();
                break;
            case 24:
                return this.valid_ue2();
                break;
            case 25:
                return this.valid_um();
                break;
            case 26:
                return this.valid_src();
                break;
            case 27:
                return this.valid_ue();
                break;
            case 28:
                return this.valid_sh02();
                break;
            case 30:
                return this.valid_therm();
                break;
            case 31:
                return this.valid_smart();
                break;
            default:
                return false;
                break;
        }
    }
    refresh()
    {
        try
        {
            if (!this.level_1.name_level_1.name_level_1||this.level_1.name_level_1.name_level_1===undefined)
            {
                return true;
            }
            else
            {
               if (this.level_1.name_level_1.address_level_1&&this.level_1.name_level_1.address_level_1!==undefined)
                {
                    this.level_1.address_level_1=this.level_1.name_level_1.address_level_1;
                }
                this.level_1.name_level_1=this.level_1.name_level_1.name_level_1;
            }
        }
        catch (err)
        {
            return false;
        }
        finally
        {
            
        }
    }
    init()
    {
        if (!this._init_status)
        {
            this.device = new device();
            this.level_1.address_level_1 = '';
            this.level_1.name_level_1 = '';
            this.level_2 = '';
            this.num_channel = '';
            this.status = '';
            this.color = '';
            this.info_channel = '';
            this.init_value = '';
            this.kt = 1;
            this.name = '';
            this.type_channel = '';
            this.division = '';
            this.history = '';
            this.calib_interval='';
            this.ia='';
            this.mac='';
            this.key='';
            this.model='';
            this.serial='';
            this.personal_num='';
            this.type_meter = 0;
            this._init_status=true;
            this.last_date = new Date(moment().format('YYYY-MM-DD' ));
            this.date_installation = new Date(moment().format('YYYY-MM-DD' ));
            this.date_shipment = new Date(moment().format('YYYY-MM-DD' ));
        }
        return true;
    }
}
class type_device
{
    constructor(arr_type)
    {
        this.list = arr_type;
    }
    checkMultipleVersions (id)
    {
        var type = this.get_type_device ( id );
        if ( isObject(type) && isObject(type.versions) && isObject(type.versions.list) )
        {
            return Object.keys(type.versions.list).length > 1 ;
        }
        return false;
    }
    get_key_first_settings_type_device ( id )
    {
        var type = this.get_type_device ( id );
        if ( isObject(type) && isObject(type.versions) )
        {
            return type.versions.first;
        }
        return undefined;
    }
    get_key_default_settings_type_device ( id, appEui )
    {
        var type = this.get_type_device ( id );
        if ( isObject(type) && isObject(type.versions) )
        {
            var defaultVersion = type.versions.default;
            
            if( isObject(type.versions.list) && appEui !== undefined )
            {
                var countMatches = 0;
                var versionId = undefined;
                for( var key in type.versions.list )
                {
                    var version = type.versions.list[key];
                    if( isObject(version) && isObject(version.appEui) )
                    {
                        if ( version.appEui.indexOf( appEui ) > -1 )
                        {
                            countMatches++;
                            versionId = version.id;
                        }
                    }
                }
                if( countMatches === 1 ) defaultVersion = versionId;
            }
            return defaultVersion;
        }
        return undefined;
    }
    get_settings_type_device ( id, version )
    {
        if(version !== undefined && version !== '' )
        {
            version = version.toString();
        }
        var type = this.get_type_device ( id );
        if ( isObject(type) && isObject(type.versions) && isObject(type.versions.list) )
        {
            if ( version === undefined || version === '' ) version = this.get_key_first_settings_type_device ( id );
            var selectedVersion = type.versions.list[version];
            if(selectedVersion == undefined && Object.keys(type.versions.list).length == 1)
            {
                //Костыль против бага что старая версия не почистилась по какой то причине
                //Был электросчетчик, удалили, создали новое устройство с новым типом, версия старая
                version = this.get_key_first_settings_type_device ( id );  
                selectedVersion = type.versions.list[version];
            }
            var settings = isObject(selectedVersion) ? type.versions.list[version].settings : [];
            var validSettings = isObject(settings) && settings.length > 0;
            if ( validSettings ) return settings;
        }
        return [];
    }
    get_info_type_device ( id, version )
    {
        if(version !== undefined && version !== '' )
        {
            version = version.toString();
        }
        var type = this.get_type_device ( id );
        if ( isObject(type) && isObject(type.versions) && isObject(type.versions.list) )
        {
            if ( version === undefined || version === '' ) version = this.get_key_first_settings_type_device ( id );
            var selectedVersion = type.versions.list[version];
            if(selectedVersion == undefined && Object.keys(type.versions.list).length == 1)
            {
                //Костыль против бага что старая версия не почистилась по какой то причине
                //Был электросчетчик, удалили, создали новое устройство с новым типом, версия старая
                version = this.get_key_first_settings_type_device ( id );  
                selectedVersion = type.versions.list[version];
            }
            var info = isObject(selectedVersion) ? type.versions.list[version].info : false;
            var validInfo = typeof info === 'boolean';
            if ( validInfo ) return info;
        }
        return false;
    }
    get_diagnostic_type_device ( id, version )
    {
        if(version !== undefined && version !== '' )
        {
            version = version.toString();
        }
        var type = this.get_type_device ( id );
        if ( isObject(type) && isObject(type.versions) && isObject(type.versions.list) )
        {
            if ( version === undefined || version === '' ) version = this.get_key_first_settings_type_device ( id );
            var selectedVersion = type.versions.list[version];
            if(selectedVersion == undefined && Object.keys(type.versions.list).length == 1)
            {
                //Костыль против бага что старая версия не почистилась по какой то причине
                //Был электросчетчик, удалили, создали новое устройство с новым типом, версия старая
                version = this.get_key_first_settings_type_device ( id );  
                selectedVersion = type.versions.list[version];
            }
            var diagnostic = isObject(selectedVersion) ? type.versions.list[version].diagnostic : false;
            var validDiagnostic = typeof diagnostic === 'boolean';
            if ( validDiagnostic ) return diagnostic;
        }
        return false;
    }
    get_settingsValues_type_device ( id, version )
    {
        if(version !== undefined && version !== '' )
        {
            version = version.toString();
        }
        var type = this.get_type_device ( id );
        if ( isObject(type) && isObject(type.versions) && isObject(type.versions.list) )
        {
            if ( version === undefined || version === '' ) version = this.get_key_first_settings_type_device ( id );
            var selectedVersion = type.versions.list[version];
            if(selectedVersion == undefined && Object.keys(type.versions.list).length == 1)
            {
                //Костыль против бага что старая версия не почистилась по какой то причине
                //Был электросчетчик, удалили, создали новое устройство с новым типом, версия старая
                version = this.get_key_first_settings_type_device ( id );  
                selectedVersion = type.versions.list[version];
            }
            var settingsValues = isObject(selectedVersion) ? type.versions.list[version].settingsValues : false;
            var validSettingsValues = typeof settingsValues === 'object';
            if ( validSettingsValues ) return settingsValues;
        }
        return false;
    }
    get_type_device ( id )
    {
        try
        {
            for (var i =0;i<this.list.length;i++)
           {
               if (this.list[i].id==id)
               {
                   return this.list[i];
               }
           }
           return false;
        }
        catch (err)
        {
            return false;
        }
    }
    get_type_device_on_appEui(appEui)
    {
        try
        {
            for (var i = 0; i < this.list.length; i++ )
            {
                var versions = this.list[i].versions;
                if( isObject(versions) && isObject(versions.list) )
                {
                    for ( var key in versions.list )
                    {
                        var version = versions.list[key];
                        if( isObject(version) && isObject(version.appEui) )
                        {
                            if ( version.appEui.indexOf( appEui ) > -1 )
                            {
                                return this.list[i];
                            }
                        }
                    }
                }
            }
            return false;
        }
        catch (err)
        {
            return false;
        }
    }
}
class type_channels
{
    constructor(arr_type)
    {
        this.list = arr_type;
    }
    get_type_channel( id )
    {
        try
        {
            for (var i =0;i<this.list.length;i++)
           {
               if (this.list[i].id==id)
               {
                   return this.list[i];
               }
           }
           return false;
        }
        catch (err)
        {
            return false;
        }
    };
}
class status_channel_list
{
    constructor(list)
    {
        this.list = list;
    }
    get_status( id )
   {
       try
       {
            for (var i =0;i<this.list.length;i++)
            {
                if (this.list[i].id==id)
                {
                    return this.list[i].name;
                }
            }
            return "-";
       }
        catch (err)
        {
            return false;
        }
   };
}
class color_list
{
    constructor(list)
    {
        this.list = list;
    }
    get_color( id )
    {
        try
        {
         for (var i =0;i<this.list.length;i++)
         {
             if (this.list[i].id==id)
             {
                 return this.list[i].hex;
             }
         }
         return "transparent";
        }
         catch (err)
         {
             return false;
         }
    };
    get_full_color( id )
    {
         try
        {
         for (var i =0;i<this.list.length;i++)
         {
             if (this.list[i].id==id)
             {
                 return this.list[i];
             }
         }
         return "transparent";
        }
         catch (err)
         {
             return false;
         }
    }
}
class Channel
{
    constructor(object)
    {
       var valid = new valid_data();
       if (!object)
       {
           object = new Object();
       }
       this.address_level_1 =object.address_level_1;
       this.name_level_1 =object.name_level_1;
       this.level_2 =object.level_2;
       this.name =object.name;
       this.num_channel =object.num_channel;
       this.status =object.status;
       this.color =object.color;
       this.info_channel =object.info_channel;
       this.init_value = object.init_value;
       this.kt =valid.isNumber(object.kt)?object.kt:1;
       this.last_date =object.last_date;
       this.date_installation = object.date_installation;
       this.date_shipment = object.date_shipment;
       this.calib_interval=object.calib_interval;
       this.ia=object.ia;
       this.mac=object.mac;
       this.key=object.key;
       this.model=object.model;
       this.serial=object.serial;
       this.personal_num=object.personal_num;
       this.type_meter = object.type_meter;
       this.type_channel =object.type_channel;
       this.history =object.history;
       this.temp_history = new Object();
       this.division =object.division;
       this.statistics=new Statistic();
       this.danger=false;
       this.security_name=object.security_name;
       this.hall_1_name=object.hall_1_name;
       this.hall_2_name=object.hall_2_name;
       this.min_t=object.min_t!==undefined?object.min_t:-55;
       this.max_t=object.max_t!==undefined?object.max_t:100;
       this.water=object.water;
       this.instrument=object.instrument;
       this.instrument2=object.instrument2;
       this.unit=object.unit;
       this.min_v=object.min_v;
       this.max_v=object.max_v;
       this.min_normal_v=object.min_normal_v;
       this.max_normal_v=object.max_normal_v;
       this.security_name_2=object.security_name_2;
       this.sensor_name_1=object.sensor_name_1;
       this.sensor_name_2=object.sensor_name_2;

        for(var i = 1; i<=10; i++)
        {
            this[`temperature_sensor_name_${i}`] = object[`temperature_sensor_name_${i}`];
        }
       
       this.provider=object.provider;
       this.typeCargo=object.typeCargo;
       this.cargo=object.cargo;
       
       this.name_sensor_in_1=object.name_sensor_in_1;
       this.name_sensor_in_2=object.name_sensor_in_2;
       this.name_sensor_out_1=object.name_sensor_out_1;
       this.name_sensor_out_2=object.name_sensor_out_2;
       
       this.state_sensor_0=object.state_sensor_0;
       this.state_sensor_1=object.state_sensor_1;
       this.telephones = object.telephones;
       this.emails = object.emails;
       this.telegram_chats = object.telegram_chats;
       this.sms = object.sms;
       this.email = object.email;
       this.telegram = object.telegram;
       this.enable_danger = object.enable_danger;
       this.user_message_danger = valid.isBool(object.user_message_danger)?object.user_message_danger:true;
       this.app_message_danger = valid.isBool(object.app_message_danger)?object.app_message_danger:false;
       this.message_sms = object.message_sms;
       this.message_messenger = object.message_messenger;
       this.voice = object.voice;
       this.voice_message = object.voice_message;
       this.count_rate=object.count_rate;
       this.count_phase = object.count_phase;
       this.display_power_profile = object.display_power_profile;
       this.relay = object.relay;
    }
    clear_history()
    {
    }
    getInfo(dateRange,filterPackage)
    {
        var my_converter = new vega_converter();
        var _items_counter = new Object();
        var dangers = new Object();
        var result = new Object();
        var version = this._self.version;
        var currentVersion = parseInt(version);
        var si21_22 = this._self.device_type==11||this._self.device_type==18;
        var si21_22rev3 = si21_22 && currentVersion >= 2;
        var si11rev2 = this._self.device_type==1 && currentVersion >= 2;
        var si12rev2 = this._self.device_type==2 && currentVersion >= 2;
        var si_i = this.type_channel>=1&&this.type_channel<=6&&this._self.device_type!=3&&!si21_22rev3&&!si12rev2;
        var si_i_rev3 = this.type_channel>=1&&this.type_channel<=6&&(si21_22rev3||si11rev2||si12rev2);
        
        


        var sh02_rev2 = this.type_channel>=1&&this.type_channel<=6&&this._self.device_type == 28 &&version>=1;
        var sh02_a_rev2 = this.type_channel==29&&this._self.device_type == 28&&version>=1;
        var sh02 = this.type_channel>=1&&this.type_channel<=6&&this._self.device_type == 28 && !sh02_rev2;
        var sh02_a = this.type_channel==29&&this._self.device_type == 28&&!sh02_a_rev2;

        var si13_pulse = this.type_channel>=1&&this.type_channel<=6&&this._self.device_type==3&&version==0; 
        var si13_pulse_rev2 = this.type_channel>=1&&this.type_channel<=6&&this._self.device_type==3&&version==1; 
        var mbus_danger = this.type_channel == 6 && ( this._self.device_type == 20 );
        var si13_m = this.type_channel==16&&version==0; 
        var si13_m_rev2 = this.type_channel==16&&version==1; 
        var mbus = this.type_channel==20;
        var sve1 = this.type_channel==8; 
        var td11 = this.type_channel==7&&version==0; 
        var td11rev2 = this.type_channel==7&&version==1;
        var tp11 = this.type_channel==9&&version==0; 
        var tp11rev2 = this.type_channel==9&&version==1; 
        
        var ue = this.type_channel==14; 
        var ug = this.type_channel==15;
        var gm1 = ug && this._self.device_type == 17;
        var smart = this.type_channel==10||this.type_channel==11||this.type_channel==12||this.type_channel==13||this.type_channel==31;
        var hs = this.type_channel==23;
        var um = this.type_channel==25;
        var ss = this.type_channel==13;
        var ss0102 = this.type_channel==31;
        var lm1 = this.type_channel==17;
        var src = this.type_channel==26;
        var tl11 = this.type_channel==18;
        
        var kt = this.kt!==undefined?this.kt:1;
        var init_value = this.init_value!==undefined?this.init_value:0;
        var division = this.division!==undefined?this.division:1;
        var min_v = parseFloat(this.min_v);
        var max_v = parseFloat(this.max_v);
        result.desc = new Object();
        result.count_all = 0;
        result.count_danger = 0;
        result.last_ts = 0;
        result.last_time = 0;
        result.meterReadings = {
            summary:
                    {
                        begin:
                        {
                            time:99999999999999,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        end:
                        {
                            time:0,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        consum:function(num)
                        {
                            return my_converter.round_size(this.end.value-this.begin.value,num);
                        }
                    },
            rate_1:
                    {
                        begin:
                        {
                            time:99999999999999,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        end:
                        {
                            time:0,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        consum:function(num)
                        {
                            return my_converter.round_size(this.end.value-this.begin.value,num);
                        }
                    },
            rate_2:
                    {
                        begin:
                        {
                            time:99999999999999,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        end:
                        {
                            time:0,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        consum:function(num)
                        {
                            return my_converter.round_size(this.end.value-this.begin.value,num);
                        }
                    },
            rate_3:
                    {
                        begin:
                        {
                            time:99999999999999,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        end:
                        {
                            time:0,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        consum:function(num)
                        {
                            return my_converter.round_size(this.end.value-this.begin.value,num);
                        }
                    },
            rate_4:
                    {
                        begin:
                        {
                            time:99999999999999,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        end:
                        {
                            time:0,
                            value:0,
                            getValue:function(num)
                            {
                                return this.value?my_converter.round_size(this.value,num):this.value;
                            }
                        },
                        consum:function(num)
                        {
                            return this.end.value-this.begin.value;
                        }
                    },
            set_value:function(cell,time,value,fcnt)
            {
                //функция приема значения
                if (time<this[cell].begin.time)
                {
                    this[cell].begin.time = time;
                    this[cell].begin.value = value;
                    this[cell].begin.fcnt = fcnt;
                }
                if (time>this[cell].end.time)
                {
                    this[cell].end.time = time;
                    this[cell].end.value = value;
                    this[cell].begin.fcnt = fcnt;
                }
            },
            converTimeToMS:function()
            {
                this.rate_1.begin.time = this.rate_1.begin.time*1000;
                this.rate_1.end.time = this.rate_1.end.time*1000;
                this.rate_2.begin.time = this.rate_2.begin.time*1000;
                this.rate_2.end.time = this.rate_2.end.time*1000;
                this.rate_3.begin.time = this.rate_3.begin.time*1000;
                this.rate_3.end.time = this.rate_3.end.time*1000;
                this.rate_4.begin.time = this.rate_4.begin.time*1000;
                this.rate_4.end.time = this.rate_4.end.time*1000;
                this.summary.begin.time = this.summary.begin.time*1000;
                this.summary.end.time = this.summary.end.time*1000;
            }
        }
        for (var i = 0; i< this.history.length;i++)
        {
            var cell_history = this.history[i];
            var type_package = cell_history.type;
            var vTs = cell_history.ts!==undefined && typeof cell_history.ts === 'number' && cell_history.ts > 0;
            var vTime = cell_history.time!==undefined && typeof cell_history.time === 'number' && cell_history.time > 0;
            var correctTimeForConsum = vTime && cell_history.time >= dateRange.getStart() && cell_history.time <= (dateRange.getEnd()+HOUR_S);
            var correctTsForConsum = vTs && cell_history.ts >= ( dateRange.getStart() * 1000 ) && cell_history.ts <= ( ( dateRange.getEnd() + HOUR_S ) * 1000 );
            // result.last_battery = cell_history.charge;
            // if(cell_history.charge!==undefined)
            // {
                // Либо с каждым отдельно разбераться либо для всех индивидуально прописывать
                // Правильно видимо индивидуально для каждого прописывать...
            // }
            if (si13_m)
            {
                var validTime = cell_history.ts!==undefined&&cell_history.ts>0;
                // var correctTime = validTime&&cell_history.ts>=(dateRange.getStart()*1000)&&cell_history.ts<=(dateRange.getEnd()*1000);
                // var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                if (validTime&&!_items_counter[cell_history.ts])
                {
                    result.count_all++;
                    if (type_package == 4)
                    {
                        if (cell_history.ts>result.last_ts)
                        {
                            result.last_ts=cell_history.ts;
                            result.last_sensor=cell_history.sensor_rate_sum*kt;
                        }
                        if (correctTsForConsum&&!_items_counter[cell_history.ts])
                        {
                            _items_counter[cell_history.ts]=true;
                            result.meterReadings.set_value('summary',moment(cell_history.ts).unix(),cell_history.sensor_rate_sum*kt,cell_history.fcnt);
                            result.meterReadings.set_value('rate_1',moment(cell_history.ts).unix(),cell_history.sensor_rate_1*kt,cell_history.fcnt);
                            result.meterReadings.set_value('rate_2',moment(cell_history.ts).unix(),cell_history.sensor_rate_2*kt,cell_history.fcnt);
                            result.meterReadings.set_value('rate_3',moment(cell_history.ts).unix(),cell_history.sensor_rate_3*kt,cell_history.fcnt);
                            result.meterReadings.set_value('rate_4',moment(cell_history.ts).unix(),cell_history.sensor_rate_4*kt,cell_history.fcnt);
                        }
                    }
                }
            }
            else if (si13_m_rev2)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                // var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                // var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                if (validTime&&!_items_counter[cell_history.time])
                {
                    result.count_all++;
                    if (type_package == 4)
                    {
                        if (cell_history.time>result.last_time)
                        {
                            result.last_time=cell_history.time;
                            result.last_sensor=cell_history.sensor_rate_sum*kt;
                        }
                        if (correctTimeForConsum&&!_items_counter[cell_history.time])
                        {
                            _items_counter[cell_history.time]=true;
                            var timeMS = cell_history.time*1000;
                            result.meterReadings.set_value('summary',cell_history.time,cell_history.sensor_rate_sum*kt,cell_history.fcnt);
                            result.meterReadings.set_value('rate_1',cell_history.time,cell_history.sensor_rate_1*kt,cell_history.fcnt);
                            result.meterReadings.set_value('rate_2',cell_history.time,cell_history.sensor_rate_2*kt,cell_history.fcnt);
                            result.meterReadings.set_value('rate_3',cell_history.time,cell_history.sensor_rate_3*kt,cell_history.fcnt);
                            result.meterReadings.set_value('rate_4',cell_history.time,cell_history.sensor_rate_4*kt,cell_history.fcnt);
                        }
                    }
                }
            }
            if (mbus)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                // var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                // var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                if (validTime&&!_items_counter[cell_history.ts])
                {
                    if (type_package == 1)
                    {
                        var currentAddress = parseInt('0x'+cell_history.address);
                        var addr = this.ia;
                        var validAddress = currentAddress==addr;
                        result.count_all++;
                        if(validAddress)
                        {
                            if (cell_history.time>result.last_time)
                            {
                                result.last_time=cell_history.time;
                                result.last_sensor=cell_history.sensor_rate_sum;
                                result.last_battery = cell_history.charge;
                            }
                            if (correctTimeForConsum&&!_items_counter[cell_history.time])
                            {
                                _items_counter[cell_history.time]=true;
                                result.meterReadings.set_value('summary',cell_history.time,cell_history.sensor_rate_sum,cell_history.fcnt);
                            }
                        }
                    }
                }
            }
            else if (si13_pulse)
            {
                result.count_all++;
                if (type_package == 1)
                {
                    var validTime = cell_history.ts!==undefined&&cell_history.ts>0;
                    // var correctTime = validTime&&cell_history.ts>=dateRange.getStart()*1000&&cell_history.ts<=dateRange.getEnd()*1000;
                    if (validTime&&!_items_counter[cell_history.ts])
                    {
                        if (cell_history.ts>result.last_ts)
                        {
                            result.last_ts=cell_history.ts;
                            result.last_sensor=cell_history.get_value(init_value,division,kt);
                            result.last_battery = cell_history.charge;

                        }
                        if (correctTimeForConsum&&!_items_counter[cell_history.ts])
                        {
                            _items_counter[cell_history.ts]=true;
                            result.meterReadings.set_value('summary',moment(cell_history.ts).unix(),cell_history.get_value(init_value,division,kt),cell_history.fcnt);
                        }
                    }
                }
                else if (type_package == 2)
                {
                    var validTime = cell_history.ts!==undefined&&cell_history.ts>0;
                    var correctTime = validTime&&cell_history.ts>=dateRange.getStart()*1000&&cell_history.ts<=dateRange.getEnd()*1000;
                    // var validSensor = cell_history.sensor!==undefined&&typeof cell_history.sensor === 'number';
                    var validNumChannel = (cell_history.num_channel+6) == this.num_channel;
                    if (correctTime&&!dangers[cell_history.ts]&&validNumChannel)
                    {
                        cell_history.primaryDanger = 'a0';
                        cell_history.dateTime = cell_history.ts;
                        dangers[cell_history.ts] = cell_history;
                        result.count_danger++;
                    }
                    if ( validTime && cell_history.time>result.last_time )
                    {
                        result.last_time=cell_history.time;
                        result.last_battery = cell_history.charge;
                    }
                }
            }
            else if (si13_pulse_rev2)
            {
                result.count_all++;
                if (type_package == 1)
                {
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    // var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                    if (validTime&&!_items_counter[cell_history.time])
                    {
                        if (cell_history.time>result.last_time)
                        {
                            result.last_time=cell_history.time;
                            result.last_sensor=cell_history.get_value(init_value,division,kt);
                            result.last_battery = cell_history.charge;

                        }
                        if (correctTimeForConsum&&!_items_counter[cell_history.time])
                        {
                            _items_counter[cell_history.time]=true;
                            result.meterReadings.set_value('summary',cell_history.time,cell_history.get_value(init_value,division,kt),cell_history.fcnt);
                        }
                    }
                }
                else if (type_package == 2)
                {
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                    // var validSensor = cell_history.sensor!==undefined&&typeof cell_history.sensor === 'number';
                    var validNumChannel = (cell_history.num_channel+6) == this.num_channel;
                    if (correctTime&&!dangers[cell_history.time]&&validNumChannel)
                    {
                        cell_history.primaryDanger = 'a0';
                        cell_history.dateTime = cell_history.time*1000;
                        dangers[cell_history.time] = cell_history;
                        result.count_danger++;
                    }
                    if ( validTime && cell_history.time>result.last_time )
                    {
                        result.last_time=cell_history.time;
                        result.last_battery = cell_history.charge;
                    }
                }
            }
            else if (sh02)
            {
                result.count_all++;
                if (type_package == 1 || type_package == 9)
                {
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                    var d1 = cell_history.reason == 2 && this.num_channel == 1;
                    var d2 = cell_history.reason == 3 && this.num_channel == 2;
                    var validNumChannel = d1 || d2;
                    if (correctTime&&!dangers[cell_history.time]&&validNumChannel)
                    {
                        cell_history.primaryDanger = 'a0';
                        cell_history.dateTime = cell_history.time*1000;
                        dangers[cell_history.time] = cell_history;
                        result.count_danger++;
                    }
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time=cell_history.time;
                        result.last_sensor=cell_history.get_value(init_value,division,kt);
                        result.last_battery = cell_history.charge;
                    }
                    if (correctTimeForConsum&&!_items_counter[cell_history.time])
                    {
                        _items_counter[cell_history.time]=true;
                        result.meterReadings.set_value('summary',cell_history.time,cell_history.get_value(init_value,division,kt),cell_history.fcnt);
                    }
                }
            }
            else if (sh02_rev2)
            {
                result.count_all++;
                if (type_package == 10)
                {
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                    var d1 = cell_history.reason == 2 && this.num_channel == 1;
                    var d2 = cell_history.reason == 3 && this.num_channel == 2;
                    var validNumChannel = d1 || d2;
                    if (correctTime&&!dangers[cell_history.time]&&validNumChannel)
                    {
                        cell_history.primaryDanger = 'a0';
                        cell_history.dateTime = cell_history.time*1000;
                        dangers[cell_history.time] = cell_history;
                        result.count_danger++;
                    }
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time=cell_history.time;
                        result.last_sensor=cell_history.get_value(init_value,division,kt);
                        result.last_battery = cell_history.charge;
                    }
                    if (correctTimeForConsum&&!_items_counter[cell_history.time])
                    {
                        _items_counter[cell_history.time]=true;
                        result.meterReadings.set_value('summary',cell_history.time,cell_history.get_value(init_value,division,kt),cell_history.fcnt);
                    }
                }
            }
            else if (sh02_a)
            {
                result.count_all++;
                if (type_package == 1 || type_package == 9)
                {
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                    
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time=cell_history.time;
                        result.last_sensor=my_converter.parse0_21mB( cell_history.sensor, min_v, max_v );
                        result.last_battery = cell_history.charge;
                    }
                }
            }
            else if (sh02_a_rev2)
            {
                result.count_all++;
                if (type_package == 10)
                {
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                    
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time=cell_history.time;
                        result.last_sensor=my_converter.parse0_21mB( cell_history.sensor, min_v, max_v );
                        result.last_battery = cell_history.charge;
                    }
                }
            }
            else if (mbus_danger)
            {
                result.count_all++;
                if (type_package == 5)
                {
                    var validTime = cell_history.ts!==undefined&&cell_history.ts>0;
                    var correctTime = validTime&&cell_history.ts>=dateRange.getStart()*1000&&cell_history.ts<=dateRange.getEnd()*1000;
                    if (correctTime&&!dangers[cell_history.ts]&&(cell_history.num_channel+10)==this.num_channel)
                    {
                        cell_history.primaryDanger = 'a0';
                        cell_history.dateTime = cell_history.ts;
                        dangers[cell_history.ts] = cell_history;
                        result.count_danger++;
                    }
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time=cell_history.time;
                        result.last_battery = cell_history.charge;
                    }
                }
            }
            else if ( si_i_rev3 && cell_history.port == 2 )
            {
                result.count_all++;
                var timeMs = cell_history.time * 1000;
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                if (validTime&&!_items_counter[cell_history.time])
                {
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time=cell_history.time;
                        result.last_sensor=cell_history.get_value(init_value,division,kt);
                        result.last_battery = cell_history.charge;
                    }
                    if (correctTimeForConsum&&!_items_counter[cell_history.time])
                    {
                        _items_counter[cell_history.time]=true;
                        result.meterReadings.set_value('summary',cell_history.time,cell_history.get_value(init_value,division,kt),cell_history.fcnt);
                    }
                    if (correctTime&&!dangers[timeMs]&&(cell_history.reason==this.num_channel || cell_history.reason == 5))
                    {
                        cell_history.primaryDanger = 'a0';
                        cell_history.dateTime = timeMs;
                        dangers[timeMs] = cell_history;
                        result.count_danger++;
                    }
                }
            }
            else if (si_i)
            {
                result.count_all++;
                if (type_package == 1)
                {
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    // var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                    if (validTime&&!_items_counter[cell_history.time])
                    {
                        if (cell_history.time>result.last_time)
                        {
                            result.last_time=cell_history.time;
                            result.last_sensor=cell_history.get_value(init_value,division,kt);
                            result.last_battery = cell_history.charge;

                        }
                        if (correctTimeForConsum&&!_items_counter[cell_history.time])
                        {
                            _items_counter[cell_history.time]=true;
                            result.meterReadings.set_value('summary',cell_history.time,cell_history.get_value(init_value,division,kt),cell_history.fcnt);
                        }
                    }
                }
                else if (type_package == 2)
                {
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                    var timeMs = cell_history.time * 1000;
                    if (correctTime&&!dangers[timeMs]&&cell_history.num_channel==this.num_channel)
                    {
                        cell_history.primaryDanger = 'a0';
                        cell_history.dateTime = timeMs;
                        dangers[timeMs] = cell_history;
                        result.count_danger++;
                    }
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time=cell_history.time;
                        result.last_battery = cell_history.charge;
                    }
                }
            }
            else if (sve1)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                if (validTime&&!_items_counter[cell_history.time])
                {
                    result.count_all++;
                    if (type_package == 1)
                    {
                        if (cell_history.time>result.last_time)
                        {
                            result.last_time=cell_history.time;
                            result.last_sensor=cell_history.sensorKB;
                            result.last_battery = cell_history.charge;
                        }
                        if(correctTimeForConsum&&!_items_counter[cell_history.time])
                        {
                            _items_counter[cell_history.time]=true;
                            result.meterReadings.set_value('summary',cell_history.time,cell_history.sensorKB,cell_history.fcnt);
                        }
                        if (correctTime)
                        {
                            cell_history.primaryDanger = '';
                            var checkEvent = false;
                            if (cell_history.state_display)
                            {
                                cell_history.primaryDanger=cell_history.primaryDanger+'a';
                                checkEvent = true;
                            }
                            if (cell_history.leaking)
                            {
                                cell_history.primaryDanger=cell_history.primaryDanger+'b';
                                checkEvent = true;
                            }
                            if (cell_history.breakthrough)
                            {
                                cell_history.primaryDanger=cell_history.primaryDanger+'c';
                                checkEvent = true;
                            }
                            if (cell_history.hall_1)
                            {
                                cell_history.primaryDanger=cell_history.primaryDanger+'d';
                                checkEvent = true;
                            }
                            if (checkEvent)
                            {
                                result.count_danger++;
                                cell_history.dateTime = cell_history.time*1000;
                                dangers[cell_history.time*1000] = cell_history;
                            }
                        }
                    }
                }
            }
            else if (td11)
            {
                var validTime = cell_history.ts!==undefined&&cell_history.ts>0;
                var correctTime = validTime&&cell_history.ts>=(dateRange.getStart()*1000)&&cell_history.ts<=(dateRange.getEnd()*1000);
                if (validTime&&!_items_counter[cell_history.ts])
                {
                    _items_counter[cell_history.ts] = true;
                    result.count_all++;
                    if (type_package == 1)
                    {
                        if (cell_history.ts>result.last_ts)
                        {
                            result.last_ts=cell_history.ts;
                            result.last_sensor=cell_history.temperature;
                            result.last_battery = cell_history.charge;
                        }
                        if ( correctTime )
                        {
                            //var checkEvent = cell_history.reason!==0;
                            //var checkTemperature = t<=t_min||t>=t_max;

                            //if ((checkEvent||checkTemperature)&&!_dangers[cell_history.ts])

                            var checkEvent = cell_history.reason!==0;
                            var t = parseFloat(cell_history.temperature);
                            var t_max = this.max_t;
                            var t_min = this.min_t;
                            var checkTemperature = t<=t_min||t>=t_max;
                            if (checkTemperature)
                            {
                                cell_history.primaryDanger = 'a';
                                cell_history.dangerTemperature = true;
                            }
                            if (checkEvent)
                            {
                                cell_history.primaryDanger = cell_history.primaryDanger?cell_history.primaryDanger+cell_history.reason:cell_history.reason;
                                cell_history.dangerEvent = true;
                            }
                            if ((checkEvent||checkTemperature)&&!dangers[cell_history.ts])
                            {
                                result.count_danger++;
                                cell_history.dateTime = cell_history.ts;
                                dangers[cell_history.ts] = cell_history;
                            }
                        }
                    }
                }
            }
            else if (td11rev2)
            {
                var validTime = cell_history.time !== undefined && cell_history.time > 0;
                var correctTime = validTime && cell_history.time >= dateRange.getStart() && cell_history.time <= dateRange.getEnd();
                if (validTime&&!_items_counter[cell_history.ts]&&correctTime)
                {
                    _items_counter[cell_history.time] = true;
                    result.count_all ++;
                    if ( type_package == 1 )
                    {
                        if ( cell_history.time > result.last_time )
                        {
                            result.last_time = cell_history.time;
                            result.last_sensor = cell_history.temperature;
                            result.last_battery = cell_history.charge;
                        }
                        var checkEvent = cell_history.reason !== 0;
                        var t = parseFloat( cell_history.temperature );
                        if ( cell_history.limit_exceeded )
                        {
                            cell_history.primaryDanger = 'a';
                            cell_history.dangerTemperature = true;
                        }
                        if ( checkEvent )
                        {
                            cell_history.primaryDanger = cell_history.primaryDanger ? cell_history.primaryDanger + cell_history.reason : cell_history.reason;
                            cell_history.dangerEvent = true;
                        }
                        if ( ( checkEvent || cell_history.limit_exceeded ) && !dangers[cell_history.time] )
                        {
                            result.count_danger++;
                            cell_history.dateTime = cell_history.time * 1000;
                            dangers[cell_history.time] = cell_history;
                        }
                    }
                }
            }
            else if (tl11)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                if (validTime&&!_items_counter[cell_history.ts])
                {
                    _items_counter[cell_history.time] = true;
                    result.count_all++;
                    var checkEvent = cell_history.reason!=='00';
                    var t = parseFloat(cell_history.temperature);
                    var t2 = parseFloat(cell_history.temperature_2);
                    var t_max = this.max_t;
                    var t_min = this.min_t;
                    var checkTemperature = t<=t_min||t>=t_max;
                    var checkTemperature2 = t2<=t_min||t2>=t_max;
                    
                    if (cell_history.time>result.last_time)
                    {
                        result.last_lime=cell_history.time;
                        result.last_sensor=cell_history.temperature;
                        result.last_sensor_2=cell_history.temperature2;
                        result.last_battery = cell_history.charge;
                    }
                    if (checkTemperature||checkTemperature2)
                    {
                        cell_history.primaryDanger = 'a';
                        cell_history.dangerTemperature = true;
                    }
                    if (checkEvent)
                    {
                        cell_history.primaryDanger = cell_history.primaryDanger?cell_history.primaryDanger+cell_history.reason:cell_history.reason;
                        cell_history.dangerEvent = true;
                    }
                    if ((checkEvent||checkTemperature)&&!dangers[cell_history.time])
                    {
                        result.count_danger++;
                        cell_history.dateTime = cell_history.time*1000;
                        dangers[cell_history.time] = cell_history;
                    }
                    result.desc.hall_1_name=this.hall_1_name;
                }
            }
            else if (tp11)
            {
                var validTime = cell_history.ts!==undefined&&cell_history.ts>0;
                var correctTime = validTime&&cell_history.ts>=(dateRange.getStart()*1000)&&cell_history.ts<=(dateRange.getEnd()*1000);
                var sensor = my_converter.parse4_20mA(cell_history.sensorTP,min_v,max_v);
                if (validTime&&!_items_counter[cell_history.ts]&&correctTime)
                {
                    result.last_battery = cell_history.charge;
                    _items_counter[cell_history.ts]=true;
                    result.count_all++;
                    if (type_package == 1)
                    {
                        if (cell_history.ts>result.last_ts)
                        {
                            result.last_ts=cell_history.ts;
                            if (cell_history.sensorTP==0)
                            {
                                result.last_sensor=undefined;
                            }
                            else
                            {
                                result.last_sensor=sensor;
                            }
                        }
                    }
                    cell_history.primaryDanger = '';
                    if (cell_history.sensor_danger_1)
                    {
                        cell_history.primaryDanger=cell_history.primaryDanger+'a';
                    }
                    else if (cell_history.sensor_danger_2)
                    {
                        cell_history.primaryDanger=cell_history.primaryDanger+'b';
                    }
                    else
                    {
                        cell_history.dangerEvent = false;
                    }
                    cell_history.dangerEvent = cell_history.sensor_danger_1||cell_history.sensor_danger_2?true:false;
                    cell_history.security_name = this.security_name;
                    cell_history.security_name_2 = this.security_name_2;
                    var min = parseFloat(cell_history.min_normal_v);
                    var max = parseFloat(cell_history.max_normal_v);
                    var min_v = parseFloat(cell_history.min_v);
                    var max_v = parseFloat(cell_history.max_v);
                    if (cell_history.sensorTP===0)
                    {
                        cell_history.dangerData = true;
                        cell_history.primaryDanger=cell_history.primaryDanger+1;
                    }
                    else if (cell_history.sensorTP<=25&&cell_history.sensorTP>=2)
                    {
                        if (sensor<=min||sensor>=max)
                        {
                            cell_history.dangerData = true;
                            cell_history.primaryDanger=cell_history.primaryDanger+1;
                        }
                    }
                    else
                    {
                       cell_history.primaryDanger=cell_history.primaryDanger+1;
                       cell_history.dangerData = true;
                    }
                    if (cell_history.dangerData||cell_history.dangerEvent)
                    {
                        if (cell_history.dangerData&&cell_history.dangerEvent)
                        {
                            cell_history.primaryDanger='0'+cell_history.primaryDanger;
                        }
                        result.count_danger++;
                        cell_history.dateTime = cell_history.ts;
                        dangers[cell_history.ts] = cell_history;
                    }
                    //есть еще и второй
                }
            }
            else if ( tp11rev2 )
            {
                var validTime = cell_history.time !== undefined && cell_history.time > 0;
                var correctTime = validTime && cell_history.time >= dateRange.getStart() && cell_history.time <= dateRange.getEnd();
                var sensor = my_converter.parse4_20mA( cell_history.sensorTP, min_v, max_v );
                cell_history.primaryDanger = '';
                cell_history.dangerEvent = false;
                cell_history.dangerData = false;
                
                if (validTime&&!_items_counter[cell_history.time]&&correctTime)
                {
                    if ( type_package == 1 )
                    {
                        result.count_all ++;
                        _items_counter[cell_history.time] = true;
                        cell_history.dateTime = cell_history.time * 1000;
                        cell_history.security_name = this.security_name;
                        cell_history.security_name_2 = this.security_name_2;
                        if ( cell_history.time > result.last_time )
                        {
                            result.last_battery = cell_history.charge;
                            result.last_ts = cell_history.ts;
                            result.last_time = cell_history.time;
                            if ( cell_history.sensorTP == 0 )
                            {
                                result.last_sensor = undefined;
                            }
                            else
                            {
                                result.last_sensor = sensor;
                            }
                        }
                        
                        if( cell_history.reason != 0 && cell_history.reason != 5)
                        {
                            cell_history.primaryDanger = cell_history.reason;
                            cell_history.dangerEvent = true;
                            dangers[cell_history.time] = cell_history;
                            result.count_danger++;
                        }
                    }
                }
            }
            else if (ue)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                if (validTime&&!_items_counter[cell_history.time]&&(filterPackage===undefined||filterPackage==type_package))
                {
                    result.count_all++;
                    if (type_package == 1)
                    {
                        if (cell_history.time>result.last_time)
                        {
                            result.last_time=cell_history.time;
                            result.last_sensor=cell_history.sensor_rate_sum;
                            result.last_kt=cell_history.kt;
                        }
                        if ( correctTimeForConsum && !_items_counter[cell_history.time] )
                        {
                            _items_counter[cell_history.time]=true;
                            result.meterReadings.set_value('summary',cell_history.time,cell_history.sensor_rate_sum,cell_history.fcnt);
                        }
                        if (correctTime)
                        {
                            cell_history.primaryDanger = '';
                            if (cell_history.event!==undefined&&cell_history.event!=1&&cell_history.event!=19)
                            {
                                result.count_danger++;
                                cell_history.primaryDanger = cell_history.event;
                                cell_history.dateTime = cell_history.time*1000;
                                dangers[cell_history.time*1000] = cell_history;
                            }
                        }
                    } 
                    else if (type_package == 4)
                    {
                        if (cell_history.time>result.last_time)
                        {
                            result.last_time=cell_history.time;
                            result.last_sensor=cell_history.sensor_rate_sum;
                            result.last_kt=cell_history.kt;
                        }
                        if (correctTimeForConsum&&!_items_counter[cell_history.time])
                        {
                            _items_counter[cell_history.time]=true;
                            result.meterReadings.set_value('summary',cell_history.time,cell_history.sensor_rate_sum,cell_history.fcnt);
                            result.meterReadings.set_value('rate_1',cell_history.time,cell_history.sensor_rate_1,cell_history.fcnt);
                            result.meterReadings.set_value('rate_2',cell_history.time,cell_history.sensor_rate_2,cell_history.fcnt);
                            result.meterReadings.set_value('rate_3',cell_history.time,cell_history.sensor_rate_3,cell_history.fcnt);
                            result.meterReadings.set_value('rate_4',cell_history.time,cell_history.sensor_rate_4,cell_history.fcnt);
                        }
                    }
                }
            }
            else if (ug)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                if (validTime&&!_items_counter[cell_history.time])
                {
                    result.count_all++;
                    if (cell_history.port == 2)
                    {
                        if (cell_history.time>result.last_time)
                        {
                            result.last_time=cell_history.time;
                            result.last_sensor=cell_history.sensor_rate_sum;
                            result.last_battery = cell_history.charge;
                        }
                        if (correctTimeForConsum&&!_items_counter[cell_history.time])
                        {
                            _items_counter[cell_history.time]=true;
                            result.meterReadings.set_value('summary',cell_history.time,cell_history.sensor_rate_sum,cell_history.fcnt);
                        }
                        if (correctTime)
                        {
                            if(gm1)
                            {
                                if(cell_history.reason!=1)
                                {
                                    cell_history.primaryDanger = cell_history.reason;
                                    result.count_danger++;
                                    cell_history.dateTime = cell_history.time*1000;
                                    dangers[cell_history.ts] = cell_history;
                                }
                            }
                            else
                            {
                                if (cell_history.reason)
                                {
                                    cell_history.primaryDanger = cell_history.reason;
                                    result.count_danger++;
                                    cell_history.dateTime = cell_history.time*1000;
                                    dangers[cell_history.ts] = cell_history;
                                }
                            }
                        }
                    }
                }
                result.desc.name_sensor_in_1=this.name_sensor_in_1;
                result.desc.name_sensor_in_2=this.name_sensor_in_2;
                result.desc.name_sensor_out_1=this.name_sensor_out_1;
                result.desc.name_sensor_out_2=this.name_sensor_out_2;
            }
            else if (ss0102)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=dateRange.getStart()&&cell_history.time<=dateRange.getEnd();
                if (validTime&&!_items_counter[cell_history.time]&&cell_history.port==2)
                {
                    _items_counter[cell_history.time] = true;
                    result.count_all++;

                    if(correctTime)
                    {
                        var isDanger =  cell_history.reason != 6 && cell_history.reason != 9 && cell_history.reason != 16;
                        if (isDanger)
                        {
                            cell_history.primaryDanger = cell_history.reason;
                            result.count_danger++;
                            cell_history.dateTime = cell_history.time * 1000;
                            dangers[cell_history.time * 1000] = cell_history;
                        }
                    }
                    
                    if (cell_history.ts>result.last_ts)
                    {
                        result.last_ts=cell_history.ts;
                    }
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time = cell_history.time;
                        result.last_reason = cell_history.reason;
                        result.last_status_fog = cell_history.status_fog;
                        result.last_status_fire = cell_history.status_fire;
                        result.last_status_test = cell_history.status_test;
                        result.last_status_guard = cell_history.status_guard;
                        result.last_status_faulm = cell_history.status_faulm;
                        result.last_status_alarm = cell_history.status_alarm;
                        result.last_status_detach = cell_history.status_detach;
                        result.last_status_common = cell_history.status_common;
                        result.last_current_mV = cell_history.current_mV;
                        result.last_current_mA = cell_history.current_mA;
                        result.last_temperature = cell_history.temperature;
                        result.last_charge = cell_history.charge;
                        result.last_charge2 = cell_history.charge2;
                        result.last_battery_select_1 = cell_history.battery_select_1;
                        result.last_battery_select_2 = cell_history.battery_select_2;
                        result.last_battery_persent_1 = cell_history.battery_persent_1;
                        result.last_battery_persent_2 = cell_history.battery_persent_2;

                        result.last_battery = cell_history.charge;
                        result.last_battery2 = cell_history.charge2;
                    }
                    
                }
            }
            else if (smart&&cell_history.version == 0)
            {
                var validTime = cell_history.ts!==undefined&&cell_history.ts>0;
                var correctTime = validTime&&cell_history.ts>=(dateRange.getStart()*1000)&&cell_history.ts<=(dateRange.getEnd()*1000);
                if (validTime&&!_items_counter[cell_history.ts]&&correctTime)
                {
                    _items_counter[cell_history.ts] = true;
                    result.count_all++;
                    if (type_package == 1)
                    {
                        if (cell_history.ts>result.last_ts)
                        {
                            result.last_ts=cell_history.ts;
                            result.last_battery = cell_history.charge;
                        }
                        if (cell_history.reason)
                        {
                            cell_history.primaryDanger = cell_history.reason;
                            result.count_danger++;
                            cell_history.dateTime = cell_history.ts;
                            dangers[cell_history.ts] = cell_history;
                        }
                    }
                }
            }
            else if (smart&&cell_history.version >= 1&&!ss&&!ss0102)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=(dateRange.getStart())&&cell_history.time<=(dateRange.getEnd());
                if (validTime&&!_items_counter[cell_history.time]&&correctTime)
                {
                    _items_counter[cell_history.time] = true;
                    result.count_all++;
                    if (type_package == 1)
                    {
                        if (cell_history.ts>result.last_ts)
                        {
                            result.last_ts=cell_history.ts;
                        }
                        if (cell_history.time>result.last_time)
                        {
                            result.last_time=cell_history.time;
                            result.last_battery = cell_history.charge;
                        }
                        if (cell_history.reason)
                        {
                            cell_history.primaryDanger = cell_history.reason;
                            result.count_danger++;
                            cell_history.dateTime = cell_history.time * 1000;
                            dangers[cell_history.time * 1000] = cell_history;
                        }
                    }
                }
            }
            else if ( hs )
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=(dateRange.getStart())&&cell_history.time<=(dateRange.getEnd());
                if (validTime&&!_items_counter[cell_history.time])
                {
                    _items_counter[cell_history.time] = true;
                    result.count_all++;
                    if (cell_history.ts>result.last_ts)
                    {
                        result.last_ts=cell_history.ts;
                    }
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time = cell_history.time;
                        result.last_damp = cell_history.damp;
                        result.last_angle = cell_history.angle;
                        result.last_temperature = cell_history.temperature;
                        result.last_battery = cell_history.charge;
                    }
                    if ( cell_history.reason > 1 && correctTime )
                    {
                        cell_history.primaryDanger = cell_history.reason;
                        result.count_danger++;
                        cell_history.dateTime = cell_history.time * 1000;
                        dangers[cell_history.time * 1000] = cell_history;
                    }
                }
            }
            else if ( um )
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=(dateRange.getStart())&&cell_history.time<=(dateRange.getEnd());
                if (validTime&&!_items_counter[cell_history.time])
                {
                    _items_counter[cell_history.time] = true;
                    result.count_all++;
                    if (cell_history.ts>result.last_ts)
                    {
                        result.last_ts=cell_history.ts;
                    }
                    if (cell_history.time>result.last_time)
                    {
                        result.last_time = cell_history.time;
                        result.last_damp = cell_history.damp;
                        result.last_angle = cell_history.angle;
                        result.last_battery = cell_history.charge;
                        result.last_lux = cell_history.lux;
                        result.last_dB = cell_history.dB;
                        result.last_CO2 = cell_history.CO2;

                        result.last_temperature = cell_history.temperature;
                    }
                    if ( cell_history.reason > 1 && correctTime )
                    {
                        cell_history.primaryDanger = cell_history.reason;
                        result.count_danger++;
                        cell_history.dateTime = cell_history.time * 1000;
                        dangers[cell_history.time * 1000] = cell_history;
                    }
                }
            }
            else if (lm1)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=(dateRange.getStart())&&cell_history.time<=(dateRange.getEnd());
                if (validTime&&!_items_counter[cell_history.time])
                {
                    _items_counter[cell_history.time] = true;
                    result.count_all++;
                    if (type_package == 1)
                    {
                        if(cell_history.time>result.last_time)
                        {
                            result.last_time = cell_history.time;
                            result.last_battery = cell_history.charge;
                        }
                        if (cell_history.ts>result.last_ts)
                        {
                            result.last_ts=cell_history.ts;
                        }
                        if (cell_history.alarm)
                        {
                            cell_history.security_name = this.security_name;
                            cell_history.primaryDanger = cell_history.alarm;
                            result.count_danger++;
                            cell_history.dateTime = cell_history.time*1000;
                            dangers[cell_history.time] = cell_history;
                        }
                    }
                }
            }
            else if (src)
            {
                var validTime = cell_history.time!==undefined&&cell_history.time>0;
                var correctTime = validTime&&cell_history.time>=(dateRange.getStart())&&cell_history.time<=(dateRange.getEnd());
                if (validTime&&!_items_counter[cell_history.time])
                {
                    _items_counter[cell_history.time] = true;
                    result.count_all++;
                    if (cell_history.ts>result.last_ts)
                    {
                        result.last_ts=cell_history.ts;
                    }
                    if (cell_history.time>result.last_time)
                    {
                        result.last_reason = cell_history.reason;
                        result.last_time = cell_history.time;
                        result.last_status_state = cell_history.status_state;
                        result.last_angle = cell_history.angle;
                        result.last_led_duty = cell_history.led_duty;
                        result.last_state_tamper = cell_history.state_tamper;
                        result.last_charge = cell_history.charge;
                        result.last_nomenal_voltage = cell_history.nomenal_voltage;

                        result.last_total_power_summary = cell_history.total_power_summary;
                        result.last_lat = cell_history.lat;
                        result.last_lng = cell_history.lng;

                        result.last_temperature = cell_history.temperature;
                        result.last_battery = cell_history.charge;
                    }
                    if ( cell_history.reason > 1 && correctTime )
                    {
                        cell_history.primaryDanger = cell_history.reason;
                        result.count_danger++;
                        cell_history.dateTime = cell_history.time * 1000;
                        dangers[cell_history.time * 1000] = cell_history;
                    }
                }
            }
        }
        if (si_i||si21_22rev3||sve1||ue||ug||td11rev2||mbus||si13_m_rev2||si13_pulse_rev2||si13_pulse||si13_m)
        {
            result.meterReadings.converTimeToMS();
        }
        if (si_i||si21_22rev3||sve1||ue||ug||td11rev2||mbus||si13_m_rev2||si13_pulse_rev2||hs||um||sh02_a||sh02||sh02_a_rev2||sh02_rev2)
        {
            result.last_datetime = result.last_time*1000;
        }
        else
        {
            result.last_datetime = result.last_ts;
        }
        if (ue&&result.last_kt!=65535)
        {
            result.kt = result.last_kt;
        }
        else
        {
            result.kt = kt;
        }
        if(mbus)
        {
            this.serial = this.ia;
        }

        result.isLowBattery = false;

        if(ss0102) 
        {
            if ( result.last_battery !== undefined && result.last_battery <= 15 ) 
            {
                result.isLowBattery = true;
            }
            if ( result.last_battery2 !== undefined && result.last_battery2 <= 15 ) 
            {
                result.isLowBattery = true;
            }
        }
        else
        {
            if ( result.last_battery !== undefined && result.last_battery <= 15 ) 
            {
                result.isLowBattery = true;
            }
        }

        result.security_name = this.security_name;
        result.security_name_2 = this.security_name_2;
        result.dangers = dangers;
        result.water = this.water;
        result.unit = this.unit;
        result.status = this.status;
        result.last_sensor = result.last_sensor?my_converter.round_size(result.last_sensor,4):undefined;
        result.consum_sum = result.meterReadings.summary.consum(4);
        result.consum_1 = result.meterReadings.rate_1.consum(4);
        result.consum_2 = result.meterReadings.rate_2.consum(4);
        result.consum_3 = result.meterReadings.rate_3.consum(4);
        result.consum_4 = result.meterReadings.rate_4.consum(4);
        result.beginReading_sum = result.meterReadings.summary.begin.getValue(4);
        result.endReading_sum = result.meterReadings.summary.end.getValue(4);
        result.beginDate_sum = result.meterReadings.summary.begin.time;
        result.endDate_sum = result.meterReadings.summary.end.time;
        result.model = this.model;
        result.serial = this.serial;
        result.name = this.name;
        result.level_2 = this.level_2;
        result.personal_num = this.personal_num;
        result.type_meter = this.type_meter;
        result.unit = this.unit;
        return result;
    }
    edit(object,dev)
    {
       var valid = new valid_data();
       this.address_level_1 =object.address_level_1;
       this.name_level_1 =object.name_level_1;
       this.level_2 =object.level_2;
       this.name =object.name;
       this.status =object.status;
       this.color =object.color;
       this.info_channel =object.info_channel;
       this.init_value =object.init_value;
       this.kt =valid.isNumber(object.kt)?object.kt:1;
       this.last_date =object.last_date;
       this.date_installation = object.date_installation;
       this.date_shipment = object.date_shipment;
       this.calib_interval=object.calib_interval;
       this.ia=object.ia;
       this.mac=object.mac;
       this.key=object.key;
       this.model=object.model;
       this.serial=object.serial;
       this.personal_num=object.personal_num;
       this.type_meter = valid.isNumber(object.type_meter)?object.type_meter:0;
       this.type_channel =object.type_channel;
       this.division =object.division;
       this.security_name=object.security_name;
       this.hall_1_name=object.hall_1_name;
       this.hall_2_name=object.hall_2_name;
       this.min_t=object.min_t!==undefined?object.min_t:-55;
       this.max_t=object.max_t!==undefined?object.max_t:100;
       this.water=object.water;  
       this.instrument=object.instrument;
       this.instrument2=object.instrument2;
       this.unit=object.unit;
       this.min_v=object.min_v;
       this.max_v=object.max_v;
       this.min_normal_v=object.min_normal_v;
       this.max_normal_v=object.max_normal_v;
       this.security_name_2=object.security_name_2;
       this.sensor_name_1=object.sensor_name_1;
       this.sensor_name_2=object.sensor_name_2;

       for(var i = 1; i<=10; i++)
        {
            this[`temperature_sensor_name_${i}`] = object[`temperature_sensor_name_${i}`];
        }
       
       this.provider=object.provider;
       this.typeCargo=object.typeCargo;
       this.cargo=object.cargo;
       
       this.name_sensor_in_1=object.name_sensor_in_1;
       this.name_sensor_in_2=object.name_sensor_in_2;
       this.name_sensor_out_1=object.name_sensor_out_1;
       this.name_sensor_out_2=object.name_sensor_out_2;
       
       this.state_sensor_0=object.state_sensor_0;
       this.state_sensor_1=object.state_sensor_1;
       this.telephones = object.telephones;
       this.emails = object.emails;
       this.telegram_chats = object.telegram_chats;
       this.sms = object.sms;
       this.email = object.email;
       this.telegram = object.telegram;
       this.enable_danger = object.enable_danger;
       this.user_message_danger = valid.isBool(object.user_message_danger)?object.user_message_danger:true;
       this.app_message_danger = valid.isBool(object.app_message_danger)?object.app_message_danger:false;
       this.message_sms = object.message_sms;
       this.message_messenger = object.message_messenger;
       this.voice = object.voice;
       this.voice_message = object.voice_message;
       this.count_rate=object.count_rate;
       this.count_phase = object.count_phase;
       this.display_power_profile = object.display_power_profile;
       this.relay = object.relay;
       this.version = object.version;
       if(isObject(dev)) this._self = dev;
       this._self.version = object.version;
    }
}
class date_range
{
    //требуется moment js
    constructor()
    {
        this.start;
        this.end;
    }
    setStart(val)
    {
        this.start = val;
    }
    setEnd(val)
    {
        this.end = val;
    }
    getStart()
    {
        return this.start;
    }
    getEnd()
    {
        return this.end;
    }
    getStartUTC()
    {
        return this.start + moment().utcOffset()*60;
    }
    getEndUTC()
    {
        return this.end + moment().utcOffset()*60;
    }
    compare_unix(date)
    {  
        return (date>=this.start&&date<=this.end)?true:false;  
    }
    compare(date,type)
    {
        if(type==2) return (date>=(this.getStartUTC()*1000)&&date<=((this.getEndUTC()+HOUR_S)*1000))?true:false; 
        return (date>=(this.start*1000)&&date<=(this.end*1000))?true:false;  
    }
    
    compare_unixUTC(date)
    {
        return (date>=this.getStartUTC()&&date<=this.getEndUTC())?true:false;  
    }
    compareUTC(date)
    {
        return (date>=(this.getStartUTC()*1000)&&date<=(this.getEndUTC()*1000))?true:false;  
    }
    
    compare_full(history,date_range)
    {
        return (history.time>=date_range.start&&history.time<=date_range.end)?true:false;  
    }
}
class Statistic
{
    constructor()
    {
       this.sum_sensor='-';
       this.chart  = new Array();
       this.chart_temperature  = new Array();
       this.chart_temperature_new = new Array();
       this.chart_sensor_new = new Array();

       this.chart_damp_new = new Array();
       this.chart_lux_new = new Array();
       this.chart_dB_new = new Array();
       this.chart_CO2_new = new Array();

       this.rssi  = new Array();
       this.snr  = new Array();
       this.date  = new Array();  
       this.consumed = undefined;
       this.avr_snr=0;
       this.avr_rssi=0;
       this.fcnt=0;
       this.last_time =0;
       this.last_chart =0;
       this.last_charge = 0;
       this.last_fcnt =0;
       this.last_sensor =0;
       this.start_sensor=0;
       this.end_sensor=0;
       this.arr_date  = new Array();
       this.arr_rssi = [];
       this.connect = [];
       this.arr_snr = [];
       this.type_channel =0;
       this.arr_value  = new Array();
       this.arr_value_4  = new Array();
       this.count_danger=0;
       this.count_danger_full=0; 
       this.last_sensorKB;
       this.last_state_display;
       this.last_leaking;
       this.last_breakthrough;
    }
}
class Events 
{
    constructor(maxLimit)
    {
        if(!maxLimit) this.maxLimit = 5000;
        else this.maxLimit = maxLimit;
        this.list = [];
    }
    createEvent(dateDevice,dateServer,type,message,title,channel,device,history)
    {
        var event = {
            dateDevice: undefined,
            dateServer: undefined,
            dateEvent: new Date().getTime(),
            type: undefined,
            message: 'unknown',
            title: 'unknown',
            channel: {},
            device: {},
            history: {},
            active:true
        };
        event.getDateEvent = function()
        {
            return moment(this.dateEvent).format('LLL');
        }
        var validDateDevice = typeof dateDevice === 'number' && dateDevice > 0;
        var validDateServer = typeof dateServer === 'number' && dateServer > 0;
        
        if(!type) type = 'info';

        if(validDateDevice) event.dateDevice = dateDevice*1000;
        if(validDateServer) event.dateServer = dateServer;
        if(type) event.type = type;
        if(message) event.message = message;
        if(title) event.title = title;
        if(channel) event.channel = channel;
        if(device) event.device = device;
        if(history) event.history = history;

        return event;
    }
    setEvent(dateTime,ts,type,message,title,channel,device,history)
    {
        if(type=='danger')
        {
            if(!title) title = 'Произошло тревожное событие';
            if(!message) 
            {
                try
                {
                    message = this.getNameDanger(channel,history);
                }
                catch (err)
                {
                    console.log('Не удалось собрать уведомление.',err);
                }
            }
        }

        var event = this.createEvent(dateTime,ts,type,message,title,channel,device,history);
        var validEvent = isObject(event) && typeof event.dateEvent === 'number';
       
        if(event && validEvent)
        {
            if(this.checkClear()) this.clearOld();
            this.list.push(event);
        }
    }
    checkClear()
    {
        return this.count() >= this.maxLimit ;
    }
    clearOld()
    {
        for( var i = 0; i<=this.count();i++ )
        {
            var event = this.list[i];
            if( typeof event !== 'object' || !event.active )
            {
                this.list.splice(i,1);
                return;
            }
        }
        this.clear();
    }
    clear()
    {
        this.list.splice(0,1);
    }
    clearAll()
    {
        this.list = [];
    }
    count()
    {
        return this.list.length;
    }
    inActiveAllChannel(channel)
    {
       if( typeof channel !== 'object' ) return;
       for(var i = 0; i<=this.count();i++)
        {
            var event = this.list[i];
            if( typeof event === 'object' && event.channel == channel) event.active = false;
        }
    }
    inActiveAll()
    {
        for(var i = 0; i<=this.count();i++)
        {
            var event = this.list[i];
            if( typeof event === 'object' ) event.active = false;
        }
    }
    countActive()
    {
        var count = 0;
        for(var i = 0; i<=this.count();i++)
        {
            var event = this.list[i];
            if( typeof event=='object' && event.active ) count++
        }
        return count;
    }
    getTextCountActive()
    {
        var text = 0;
        var count = this.countActive();
        if( count > 0 ) text = count;
        if( count > 9 ) text = '9+';
        return text;
    }
    getNameDanger(channel,history)
    {

        var scope = angular.element('body').scope();;

        var result = 'Неизвестное тревожное событие';
        if ( typeof channel !== 'object' && typeof channel._self !== 'object' ) return result;
        var device = channel._self;
        var cid = channel.type_channel;
        var reason = history.reason;
        var nameChannel = channel.name;
        var version = device.version!==undefined?device.version.toString():device.version;
        var currentVersion = -1;
        if(version) version = parseInt(version);
        if(!isNaN(version)) currentVersion = version;

        var sve = cid == 8;
        var mc0101 = cid == 10;
        var as0101 = cid == 11;
        var ms0101 = cid == 12;
        var ss0101 = cid == 13;
        var ss0102 = cid == 31;
        var hs0101 = cid == 23;
        var um0101 = cid == 25;
        
        
        var si21_22rev3 = (device.device_type == 11 || device.device_type == 18) && currentVersion>=2;
        var si12_rev2 = device.device_type == 2 && currentVersion>=2; 
        var td11 = device.device_type == 4;
        var tp11 = device.device_type == 5;
        var lm1 = device.device_type == 14;
        var ue = device.device_type == 12;
        var gm2 = device.device_type == 13;
        var tl11 = device.device_type == 15;
        var gm1 = device.device_type == 17;
        var mbus = device.device_type == 21 || device.device_type == 20;
        var spbzip = device.device_type == 24;
        var ue_merc = device.device_type == 27;
        var sh02 = device.device_type == 28;
        var dangerChannel = cid == 6;
       

        var instrument_1 = channel.instrument;
        var instrument_2 = channel.instrument2;
        var security_name_1 = channel.security_name;
        var security_name_2 = channel.security_name_2;
        var name_sensor_in_1 = channel.name_sensor_in_1;
        var name_sensor_in_2 = channel.name_sensor_in_2;
        var name_sensor_out_1 = channel.name_sensor_out_1;
        var name_sensor_out_2 = channel.name_sensor_out_2;

        var state = '-';

        if ( mc0101 )
        {
            
            if( !instrument_1 ) instrument_1 = 'Магнитный датчик №1';
            if( !instrument_2 ) instrument_2 = 'Магнитный датчик №2';
            

            if( reason === 0 )
            {
                result = `По времени`;
            }
            else if ( reason === 1 )
            {
                state = history.state_sensor_0?'Закрыт':'Открыт';
                result = `${instrument_1} ${state}`;
            }
            else if ( reason === 2 )
            {
                state = history.state_sensor_1?'Закрыт':'Открыт';
                result = `${instrument_2} ${state}`;
            }
        }
        else if ( as0101 )
        {
            if( reason === 0 )
            {
                result = `По времени`;
            }
            else if ( reason === 1 )
            {
                result = 'Сработал датчик движения';
            }
        }
        else if ( ms0101 )
        {
            if (reason===0)
            {
                result = 'По времени';
            } 
            else if (reason===1)
            {
                result = 'Сработал по тревоге';
            }
            else if (reason===2)
            {
                result = 'По автопостановке на охрану';
            }
        }
        else if ( ss0101 )
        {
            if (reason===0)
            {
                result = 'По времени';
            } 
            else if (reason===1)
            {
                result = 'Задымление';
            }
            else if (reason===2)
            {
                result = 'Сработал магнитый датчик';
            }
        }
        else if ( ss0102 )
        {
            if (reason===16)
            {
                result = 'По времени';
            } 
            else if (reason===5)
            {
                result = 'Тревога по обнаружению пожара';
            }
            else if (reason===6)
            {
                result = 'Тест';
            }
            else if (reason===7)
            {
                result = 'Тревога по солидарной линии работы';
            }
            else if (reason===8)
            {
                result = 'Снятие с крепежной платформы';
            }
            else if (reason===9)
            {
                result = 'Сброс тревоги';
            }
            else if (reason===10)
            {
                result = 'Низкий заряд АКБ';
            }
            else if (reason===11)
            {
                result = 'Постановка на охрану';
            }
            else if (reason===12)
            {
                result = 'Стоп охраны датчика';
            }
            else if (reason===13)
            {
                result = 'Отключение охраны';
            }
            else if (reason===14)
            {
                result = 'Ошибка датчика';
            }
            else if (reason===15)
            {
                result = 'Запыленность камеры датчика';
            }
        }
        else if ( hs0101 )
        {
            if( !security_name_1 ) security_name_1 = 'По датчику открытия №1';
            if( !security_name_2 ) security_name_2 = 'По датчику открытия №2';

            if (reason===1)
            {
                result = 'По времени';
            } 
            else if (reason===2)
            {
                result = `${security_name_1} ${history.sensor_in_1?'Закрыт':'Открыт'}`;
            }
            else if (reason===3)
            {
                result = `${security_name_2} ${history.sensor_in_2?'Закрыт':'Открыт'}`;
            }
            else if (reason===4)
            {
                result = 'По акселерометру';
            }
            else if (reason===5)
            {
                result = `По выходу влажности за установленные пороги ${history.damp} %`;
            }
            else if (reason===6)
            {
                result = `По выходу температуры за установленные пороги ${history.temperature}°C`;
            }
        }
        else if ( um0101 )
        {
            if (reason===1)
            {
                result = 'По времени';
            } 
            else if (reason===2)
            {
                result = `По выходу СО2 за установленные пороги, ${history.CO2}`;
            }
            else if (reason===3)
            {
                // if(channel.security_name_2) return channel.security_name;
                result = `По выходу уровня освещенности за установленные пороги, ${history.lux}lux`;
            }
            else if (reason===4)
            {
                result = 'По акселерометру';
            }
            else if (reason===5)
            {
                result = `По выходу влажности за установленные пороги, ${history.damp}%`;
            }
            else if (reason===6)
            {
                result = `По выходу температуры за установленные пороги, ${history.temperature}°C`;
            }
            else if (reason===7)
            {
                result = `По выходу уровня шума за определенные пороги, ${history.dB}dB`;
            }
            else if (reason===8)
            {
                result = 'Обнаружение снятия';
            }
        }
        else if ( gm2 )
        {
            if( !name_sensor_in_1 ) name_sensor_in_1 = `Вход №1`;
            if( !name_sensor_in_2 ) name_sensor_in_2 = `Вход №2`;
            if( !name_sensor_out_1 ) name_sensor_out_1 = `Изменение состояния выхода №1`;
            if( !name_sensor_out_2 ) name_sensor_out_2 = `Изменение состояния выхода №2`;

            switch (reason) {
                case 0:
                    return 'По времени'
                    break;
                case 1:
                    result = `${name_sensor_in_1} ${history.sensor_in_1?'Да':'Нет'}`;
                    break;
                case 2:
                    result = `${name_sensor_in_2} ${history.sensor_in_2?'Да':'Нет'}`;
                    break;
                case 3:
                    result = `${name_sensor_out_1} ${history.sensor_out_1?'Вкл':'Выкл'}`;
                    break;
                case 4:
                    result = `${name_sensor_out_2} ${history.sensor_out_2?'Вкл':'Выкл'}`;
                    break;
                case 5:
                    result = 'Магнитное воздействие'
                    break;
                case 6:
                    result = 'Вскрытие корпуса'
                    break;
                default:
                    result = 'Неизвестная причина'    
                    break;
            }
        }
        else if ( gm1 )
        {
            return 'Тревога';
        }
        else if ( lm1 )
        {
            if ( history.alarm ) result = 'Тревога';
        }
        // else if ( mbus )
        // {
        //     if ( history.type_package == 5 ) result = 'Тревога! ';
        //     if ( typeof history.sensors == 'object' )
        //     {
        //         var sensor = history.sensors['sensor_'+history.num_channel];
        //         if ( typeof sensor == 'number' ) result = sensor?'Замкнут':'Разомкнут';
        //     }
        // }
        else if ( sve )
        {
            var checkEvent = history.state_display||history.leaking||history.breakthrough||history.hall_1;
            if(checkEvent)
            {
                result = '';
                if(history.state_display) result+='Блокировка дисплея; ';
                if(history.leaking) result+='Протечка; ';
                if(history.breakthrough) result+='Прорыв; ';
                if(history.breakthrough) result+='Магнитное воздействие; ';
            }
        }
        else if ( ue )
        {
            if (history.type_package==1&&history.event!==undefined&&history.event!=1&&history.event!=19)
            {
                result = scope.getText_ReasonUE(history.event,12);
            }
        }
        else if ( spbzip )
        {
            if (history.type_package==1&&history.event!==undefined&&history.event!=1&&history.event!=19)
            {
                result = scope.getText_ReasonUE(history.event,24);
            }
        }
        else if ( ue_merc )
        {
            if (history.type_package==1&&history.event!==undefined&&history.event!=1&&history.event!=19)
            {
                result = scope.getText_ReasonUE(history.event,27);
            }
        }
        else if ( tl11 ) 
        {
            var checkEvent = history.reason!=='00';
            var t = parseFloat(history.temperature);
            var t2 = parseFloat(history.temperature_2);
            var t_max = channel.max_t;
            var t_min = channel.min_t;
            var checkTemperature = t<=t_min||t>=t_max;
            var checkTemperature2 = t2<=t_min||t2>=t_max;
            if ( checkEvent || checkTemperature || checkTemperature2 )
            {
                var result = '';
                if ( checkEvent )
                {
                    if ( history.reason == '01' ) result+='Корпус вскрыт; ';
                    else if ( history.reason == '10' ) result+='Магнитное воздействие №1; ';
                    else if ( history.reason == '11' ) result+='Магнитное воздействие №2; ';
                    else result+='Неизвестная причина отправки пакета; ';
                }
                if ( checkTemperature ) result+=`Температура №1 вышла за пороги, ${t}°C. `;
                if ( checkTemperature2 ) result+=`Температура №2 вышла за пороги, ${t2}°C. `;
            }
        }
        else if ( td11 )
        {
            var checkEvent = reason !== 0;
            var checkTemperature = false;
            var checkEvent = false;
            switch (reason) {
                case 0:
                    state = 'По времени';
                    break;
                case 1:
                    state = 'Охранный вход';
                    break;
                case 2:
                    state = 'Корпус вскрыт';
                    break;
                case 3:
                    state = 'Сработал датчик холла 1';
                    break;
                case 4:
                    state = 'Сработал датчик холла 2';
                    break;
                case 5:
                    state = 'Превышен лимит температуры';
                    break;
                default:
                    state = 'Неизвестная причина';
                    break;
            }
            if( currentVersion >= 1 )
            {
                checkEvent = reason !== 0;
                var t = parseFloat(history.temperature);
                checkTemperature = history.limit_exceeded;
            }
            else
            {
                checkEvent = history.reason !== 0;
                var t = parseFloat(history.temperature);
                var t_max = channel.max_t;
                var t_min = channel.min_t;
                checkTemperature = t<=t_min||t>=t_max;
            }
            if ( checkTemperature && checkEvent )
            {
                result = `${state}, температура вышла за пороги, ${history.temperature}°C.`;
            }
            else if ( checkTemperature )
            {
                result = `Температура вышла за пороги, ${history.temperature}°C.`;
            }
            else if ( checkEvent )
            {
                result = state;
            }
        }
        else if ( tp11 )
        {
            if( !security_name_1 ) security_name_1 = 'Охранный вход №1';
            if( !security_name_2 ) security_name_2 = 'Охранный вход №2';
            var s = parseFloat(history.sensorTP);
            if( currentVersion >= 1 )
            {
                state = '';
                switch (reason) {
                    case 0:
                        state = 'По времени';
                        break;
                    case 1:
                        state = channel.security_name+(history.sensor_danger_1?' Да':' Нет');
                        break;
                    case 2:
                        state = channel.security_name_2+(history.sensor_danger_2?' Да':' Нет');
                        break;
                    case 3:
                        state = 'Изменилось состояние внешнего питания';
                        break;
                    case 4:
                        state =`Показания за пределами лимита, ${scope.get_value4_20mA(s)}${channel.unit}`;
                        break;
                    case 5:
                        state = 'По запросу';
                        break;
                    default:
                        state = 'Неизвестная причина'    
                        break;
                }
                result = state;
            }
            else if ( currentVersion == 0 )
            {
                var dangerEvent = history.sensor_danger_1||history.sensor_danger_2?true:false;
                var validValue = s!==undefined&&typeof s === 'number';
                var sensorEvent = false;
                var min = parseFloat(channel.min_normal_v);
                var max = parseFloat(channel.max_normal_v);
                var min_v = parseFloat(channel.min_v);
                var max_v = parseFloat(channel.max_v);
                var resVal = undefined;
                if (validValue&&!isNaN(min)&&!isNaN(max)&&!isNaN(min_v)&&!isNaN(max_v))
                {
                    resVal = scope.get_value4_20mA(s);
                    if (s===0)
                    {
                        sensorEvent = true;
                    }
                    else if (s<=25&&s>=2)
                    {
                        var newvalue = scope.my_converter.parse4_20mA(s,min_v,max_v);
                        if (typeof newvalue === 'number')
                        {
                            if (newvalue<=min||newvalue>=max)
                            {
                                sensorEvent = true;
                            }
                        }
                    }
                    else
                    {
                        sensorEvent = true; 
                    }
                    if (resVal!=='Неизвестно')
                    {
                        if (resVal<=min||resVal>=max)
                        {
                            sensorEvent = true;
                        }
                    }
                }
                if ( sensorEvent || dangerEvent )
                {
                    state = `${security_name_1} ${history.sensor_danger_1?'Да':'Нет'}, ${security_name_2} ${history.sensor_danger_2?'Да':'Нет'}`;
                    if ( sensorEvent && checkEvent )
                    {
                        result = `${state}, показания вышли за пороги, ${resVal}${channel.unit}`;
                    }
                    else if ( sensorEvent )
                    {
                        result = `Показания вышли за пороги, ${resVal}${channel.unit}`;
                    }
                    else if ( checkEvent )
                    {
                        result = state;
                    }
                }
            }
        }
        else if ( sh02 )
        {
            var validEvent =  (history.reason == 2 && channel.num_channel == 1) || (history.reason == 3 && channel.num_channel == 2) ;
            if ( validEvent ) result = 'Тревога!';
        }
        else if ( si12_rev2 )
        {
            if(reason >= 1 && reason <= 4 && history.port == 2 ) 
            {
                state = history.sensor==1?'Замкнуто':'Разомкнуто';
                result = state;
            }
            else if(reason == 1 && history.port == 5 ) 
            {
                result = `Изменилось состояние внешнего питания`;
            }
            else if(reason >= 5 && reason <= 8)
            {
                result = `Импульсный вход ${reason-4} вышел за заданные пороги`;
            }
        }
        else if ( si21_22rev3 )
        {
            if(reason >= 1 && reason <= 4 ) 
            {
                state = history.sensor==1?'Замкнуто':'Разомкнуто';
                result = state;
            }
            else
            {
                result = `Температура вышла за пороги, ${history.temperature}°C`;
            }
        }
        else if ( dangerChannel )
        {
            state = history.sensor==1?'Замкнуто':'Разомкнуто';
            result = state;
        }

        return `Тревога! На устройстве ${nameChannel} - ${result}`;
    }
}
// class Events 
// {
//     constructor()
//     {
//         this.list = new Array();
//     }
//     setEvent(ts,device,channel,history,type)
//     {
//         var event = new Event();
//         this.list.push(event);
//     }
//     getCount()
//     {
//         return this.list.length;
//     }
// }
// class Event
// {
//     constructor(ts,device,channel,history,type)
//     {
        
//     }
// }
class Logs
{
    constructor()
    {
        this.list = new Array();
        this.full_list = new Array();
    }
    set_log(event,device,mess)
    {
        var newlog={
            mess:mess,
            event:event,
            device:device,
            time:new Date().getTime(),
            time_ru:moment().format('LTS' ).replace(',',' ' )
        };
        if (this.list.length>=10)
        {
            this.list.splice(0,1);
        }
        this.list.push(newlog);
        this.full_list.push(newlog);
    }
}
class Devices 
{
    constructor()
    {
        this.devices_list = new Array();
        this.full_devices_list = new Array();
        this.select_channel_temp=new Object();
        this.select_device_devEui='';//Выбранное устройство
        this.select_device_channel='';//Выбранный канал
        this.all_channel_list = new Array();
        this.group_list=new Object();
    }
    selectGroup(nameGroup)
    {
        for(var i = 0;i<this.group_list.length;i++)
        {
            var group = this.group_list[i];
            if (group.title == nameGroup)
            {
                group.toggle = true;
            }
            else
            {
                group.toggle = false;
            }
        }
    }
    countSelectedGroup()
    {
        var count = 0;
        for(var i = 0;i<this.group_list.length;i++)
        {
            var group = this.group_list[i];
            if (group.toggle)count++;
        }
        return count;
    }
    unselectAllGroup()
    {
        for(var i = 0;i<this.group_list.length;i++)
        {
            var group = this.group_list[i];
            group.toggle = false;
        }
    }
    groupingDevice()
    {
        var oldList = this.group_list;
        var oldGrups = new Object();
        for (var i = 0; i<oldList.length;i++)
        {
            var group = oldList[i].title;
            oldGrups['group_'+group] = oldList[i];
        }
        var groups = new Object();
        for(var i = 0; i<this.full_devices_list.length;i++)
        {
            var dev = this.full_devices_list[i];
            if ( isObject(dev) )
            {
                var group = dev.group!==undefined&&dev.group!==''?dev.group:'Other';
                var id = 0;
                if (!groups['group_'+group])
                {
                    groups['group_'+group] = {
                        devices:[],
                        id:id,
                        toggle:oldGrups['group_'+group]!==undefined?oldGrups['group_'+group].toggle:false,
                        title:group 
                    };
                    id++;
                }
                groups['group_'+group].devices.push(dev);
            }
        }
        var arr = [];
        for(var key in groups)
        {
            if (key=='group_Other'&&arr[0])
            {
                var first=arr[0];
                arr[0]=groups[key];
                arr.push(first);
            }
            else
            {
                arr.push(groups[key]);
            }
        }
        if (arr.length>0&& isObject(arr[0]) &&arr[0].title == 'Other' )
        {
            var temp = arr[0];
            arr.splice(0,1);
            arr.push(temp);
        }
        this.group_list = arr;
    }
    getPresenceTypeChannel(type)
    {
        for(var i = 0; i<this.devices_list.length;i++)
        {
            var dev = this.devices_list[i];
            if ( dev && isObject(dev.channels) )
            {
                for(var key in dev.channels)
                {
                    var channel = dev.channels[key];
                    if (channel.type_channel == type)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    getPointsMapsSelectedDevice(mode)
    {
        var temp = new Object();
        var channel = this.select_channel_temp;
        if (channel.devEui&&channel.name&&channel.num_channel!==undefined)
        {
            var statistics = channel.statistics;
            if (mode=='last' )
            {
                if (statistics.last_coordinate.time)
                {
                    var time = statistics.last_coordinate.time;
                    var lat = statistics.last_coordinate.lat;
                    var lng = statistics.last_coordinate.lng;
                    temp[time] = {
                        lat:lat,
                        lng:lng,
                        message:moment.unix(time).format('LLL' )
                    }
                }
            }
            else if (mode=='all' )
            {
                if (statistics.arr_valid_coordinates)
                {
                    for(var key in statistics.arr_valid_coordinates)
                    {
                        var location = statistics.arr_valid_coordinates[key];
                        if (!location) continue;
                        var time = location.time;
                        var lat = location.lat;
                        var lng = location.lng;
                        temp[time] = {
                            lat:lat,
                            lng:lng,
                            message:moment.unix(time).format('LLL' )
                        }
                    }
                }
                
            }
            else if (mode=='track' )
            {
                var latlngs = [];
                var latlngs_arr = [];
                var paths = new Object();
                if (statistics.arr_valid_coordinates)
                {
                    for(var key in statistics.arr_valid_coordinates)
                    {
                        var location = statistics.arr_valid_coordinates[key];
                        if (!location) continue;
                        var time = location.time;
                        var lat = location.lat;
                        var lng = location.lng;
                        if (lat&&lng)
                        {
                            latlngs_arr.push( [lat,lng]);
                            latlngs.push({lat:lat,lng: lng});
                            paths[key] =
                            {
                                weight: 2,
                                color: '#0bbce2',
                                latlngs: {
                                        lat:lat,
                                        lng:lng
                                },
                                radius: 3,
                                type: 'circle',
                                opacity:1,
                                stroke:false,
                                fillOpacity:1,
                            }
                            paths[key+'_'] =
                            {
                                weight: 10,
                                color: '#0bbce2',
                                latlngs: {
                                        lat:lat,
                                        lng:lng
                                },
                                radius: 10,
                                type: 'circle',
                                message:moment.unix(time).format('LLL' ),
                                stroke:false,
                                fillOpacity:0
                            }
                        }
                    }
                    var decorations = new Object();
                    decorations[0] = 
                    {
                        coordinates:latlngs_arr,
                        patterns: [
                            {
                                offset: '10%',
                                repeat: 150,
                                symbol: L.Symbol.arrowHead({
                                    pixelSize: 5,
                                    polygon: false, 
                                    pathOptions: {
                                        stroke: true,
                                        className:'cursorOne',
                                        color:'#0bbce2'
                                    }
                                })
                            }
                        ]
                    }
                    paths[0] = {
                        type: "polyline",
                        weight:3,
                        color:'#0bbce2',
                        latlngs:latlngs,
                        stroke: true,
                        lineCap:'round',
                        lineJoin:'round',
                        zIndexOffset:0,
                        bubblingMouseEvents:false,
                        interactive:false,
                        className:'cursorOne',
                        fillOpacity:0.2,
                        opacity:0.8
                    };
                    temp = 
                    {
                        decorations:decorations,
                        paths:paths,
                        coordinates:latlngs
                    }
                }
                
            }
            //расписать другие режимы 
        }
        return temp;
    }
    delete_device(devEui)
    {
        for (var i = 0; i<this.devices_list.length;i++)
        {
            if (this.devices_list[i].devEui==devEui)
            {
                 this.devices_list.splice(i,1);
            }
        }
        return false;
    }
    reload_all_channel_list()
    {
        var temp = new Array();
        for (var i =0; i<this.devices_list.length;i++)
        {
            for (var j=0;j<this.devices_list[i].channels.length;j++)
            {
                if (this.devices_list[i].channels[j].name)
                {
                    var tempObj = new Object();
                    tempObj.devEui = this.devices_list[i].devEui;
                    tempObj.channel=this.devices_list[i].channels[j];
                    temp.push(tempObj);
                }
            }
        }
        this.all_channel_list=temp;
    }
    get_editDevice(device,num,color,dev_type)
    {
        var valid = new valid_data();
        var editDevice = new edit_device();
        var channel = this.get_channel(device.devEui,num);
        editDevice.name=channel.name;
        editDevice.device = device;
        editDevice.version = device.version;
        editDevice.level_1.address_level_1 = channel.address_level_1;
        editDevice.level_1.name_level_1 = channel.name_level_1;
        editDevice.level_2 = channel.level_2;
        editDevice.name = channel.name;
        editDevice.num_channel = channel.num_channel;
        editDevice.status = channel.status;
        editDevice.color = color;
        editDevice.info_channel = channel.info_channel;
        editDevice.init_value = channel.init_value;
        editDevice.kt = valid.isNumber(channel.kt)?channel.kt:1;
        editDevice.calib_interval = channel.calib_interval;
        editDevice.ia = channel.ia;
        editDevice.mac = channel.mac;
        editDevice.key = channel.key;
        editDevice.model = channel.model;
        editDevice.serial = channel.serial;
        editDevice.personal_num = channel.personal_num;
        editDevice.type_meter = valid.isNumber(channel.type_meter)?channel.type_meter:0;
        editDevice.division = channel.division;
        editDevice.type_channel = dev_type;
        editDevice.last_date = new Date(moment(channel.last_date).format('YYYY-MM-DD' ));
        editDevice.date_installation = new Date(moment(channel.date_installation).format('YYYY-MM-DD' ));
        editDevice.date_shipment = new Date(moment(channel.date_shipment).format('YYYY-MM-DD' ));
        editDevice.history = channel.history;
        editDevice.security_name = channel.security_name;
        editDevice.hall_1_name = channel.hall_1_name;
        editDevice.hall_2_name = channel.hall_2_name;
        editDevice.min_t = channel.min_t;
        editDevice.max_t = channel.max_t;
        editDevice.min_t=channel.min_t!==undefined?channel.min_t:-55;
        editDevice.max_t=channel.max_t!==undefined?channel.max_t:100;
        editDevice.water=channel.water;
        editDevice.instrument = channel.instrument;
        editDevice.instrument2 = channel.instrument2;
        editDevice.unit = channel.unit;
        editDevice.min_v = channel.min_v;
        editDevice.max_v = channel.max_v;
        editDevice.min_normal_v = channel.min_normal_v;
        editDevice.max_normal_v = channel.max_normal_v;
        editDevice.security_name_2 = channel.security_name_2;
        editDevice.sensor_name_1 = channel.sensor_name_1;
        editDevice.sensor_name_2 = channel.sensor_name_2;
        for(var i = 1; i<=10; i++)
        {
            editDevice[`temperature_sensor_name_${i}`] = channel[`temperature_sensor_name_${i}`];
        }
        
        editDevice.provider=channel.provider;
        editDevice.typeCargo=channel.typeCargo;
        editDevice.cargo=channel.cargo;
        
        editDevice.name_sensor_in_1=channel.name_sensor_in_1;
        editDevice.name_sensor_in_2=channel.name_sensor_in_2;
        editDevice.name_sensor_out_1=channel.name_sensor_out_1;
        editDevice.name_sensor_out_2=channel.name_sensor_out_2;
        
        editDevice.state_sensor_0 = channel.state_sensor_0;
        editDevice.state_sensor_1 = channel.state_sensor_1;
        editDevice.telephones = channel.telephones;
        editDevice.emails = channel.emails;
        editDevice.telegram_chats = channel.telegram_chats;
        editDevice.sms = channel.sms;
        editDevice.email = channel.email;
        editDevice.telegram = channel.telegram;
        editDevice.enable_danger = channel.enable_danger;
        editDevice.user_message_danger = valid.isBool(channel.user_message_danger)?channel.user_message_danger:true;
        editDevice.app_message_danger = valid.isBool(channel.app_message_danger)?channel.app_message_danger:false;
        editDevice.message_sms = channel.message_sms;
        editDevice.message_messenger = channel.message_messenger;
        editDevice.voice = channel.voice;
        editDevice.voice_message = channel.voice_message;
        editDevice.count_rate=channel.count_rate;
        editDevice.count_phase = channel.count_phase;
        editDevice.display_power_profile = channel.display_power_profile;
        editDevice.relay = channel.relay;
        return editDevice;
    }

    add_history_multi(json,index,date,newData)
    {
        var dev = this.devices_list[index];
        var my_converter = new vega_converter();
        if (dev)
        {
            var channel1 = dev.channels[6]?dev.channels[6]:new Channel();
            var channel2 = dev.channels[7]?dev.channels[7]:new Channel();
            var channel3 = dev.channels[10]?dev.channels[10]:new Channel();
            var channel4 = dev.channels[11]?dev.channels[11]:new Channel();
            var ts = json.ts;
            var date_installation1 = channel1.date_installation?parseInt(moment(channel1.date_installation).startOf('day' ).format('x' )):0;
            var date_installation2 = channel2.date_installation?parseInt(moment(channel2.date_installation).startOf('day' ).format('x' )):0;
            var validDateInit1 = !date_installation1||ts>date_installation1;
            var validDateInit2 = !date_installation2||ts>date_installation2;
            if (dev.device_type==3) // si13
            {
                if (newData.type_package==4)
                {
                    var res  = new cell_history(json,newData,1,dev.device_type,dev.version);
                    for (var key in this.devices_list[index].channels)
                    {
                        var ia;
                        var channel = this.devices_list[index].channels[key];
                        if (res.address!==undefined)
                        {
                            ia = parseInt(res.address,16);
                            if (!isNaN(ia)&&ia==channel.ia)
                            {
                                channel.history.push(res);
                            }
                        }
                    }
                }
                else if (newData.type_package==6)
                {
                    var res  = new cell_history(json,newData,1,dev.device_type,dev.version);
                    for (var key in this.devices_list[index].channels)
                    {
                        var ia;
                        var channel = this.devices_list[index].channels[key];
                        if (res.address!==undefined)
                        {
                            ia = parseInt(res.address,16);
                            if (!isNaN(ia)&&ia==channel.ia)
                            {
                                channel.history.push(res);
                            }
                        }
                    }
                }
                else if (newData.type_package==1)
                {
                    var res1  = new cell_history(json,newData,7,dev.device_type,dev.version);
                    var res2  = new cell_history(json,newData,8,dev.device_type,dev.version);
                    if (validDateInit1)
                    {
                        if (!channel1.temp_history) channel1.temp_history = new Object();
                        if (channel1.temp_history[res1.ts]===undefined||!channel1.temp_history[res1.ts])
                        {
                           channel1.temp_history[res1.ts]=true;
                           channel1.history.push(res1);
                        }
                        else
                        {
                            if (channel1.type_channel==6)
                            {
                                channel1.history.push(res1);
                            }
                        }
                    }
                    if (validDateInit2)
                    {
                        if (!channel2.temp_history) channel2.temp_history = new Object();
                        if (channel2.temp_history[res2.ts]===undefined||!channel2.temp_history[res2.ts])
                        {
                           channel2.temp_history[res2.ts]=true;
                           channel2.history.push(res2);
                        }
                        else
                        {
                            if (channel2.type_channel==6)
                            {
                                channel2.history.push(res2);
                            }
                        }
                    }                 
                }
                else if (newData.type_package==2)
                {
                    var res1  = new cell_history(json,newData,7,dev.device_type,dev.version);
                    var res2  = new cell_history(json,newData,8,dev.device_type,dev.version);
                    if (channel1.temp_history[res1.ts]===undefined||!channel1.temp_history[res1.ts]&&validDateInit1)
                    {
                       channel1.temp_history[res1.ts]=true;
                       channel1.history.push(res1);
                    }
                    else
                    {
                        if (res1.num_channel==1)
                        {
                            channel1.history.push(res1);
                        }
                    }
                    if (channel2.temp_history[res2.ts]===undefined||!channel2.temp_history[res2.ts]&&validDateInit2)
                    {
                       channel2.temp_history[res2.ts]=true;
                       channel2.history.push(res2);
                    }
                    else
                    {
                        if (res2.num_channel==2)
                        {
                            channel2.history.push(res2);
                        }
                    }
                    if (res1.ts>=dev.last_data_ts&&res1.ts.toString().length<=13)
                    {
                        dev.last_data_ts=res1.ts;
                    }
                }
            }
            else if (dev.device_type==20 || dev.device_type==21) //m-bus-x
            {
                if (newData.type_package==1)
                {
                    var res  = new cell_history(json,newData,1,dev.device_type,dev.version);
                    for (var key in this.devices_list[index].channels)
                    {
                        var ia;
                        var channel = this.devices_list[index].channels[key];
                        if (res.address!==undefined)
                        {
                            ia = parseInt(res.address,16);
                            if (!isNaN(ia)&&ia==channel.ia)
                            {
                                channel.history.push(res);
                            }
                        }
                    }
                }
                else if (newData.type_package==5)
                {
                    var res1  = new cell_history(json,newData,11,dev.device_type,dev.version);
                    var res2  = new cell_history(json,newData,12,dev.device_type,dev.version);
                    if (channel3.temp_history[res1.ts]===undefined||!channel3.temp_history[res1.ts])
                    {
                       channel3.temp_history[res1.ts]=true;
                       channel3.history.push(res1);
                    }
                    else
                    {
                        if (res1.num_channel==1)
                        {
                            channel3.history.push(res1);
                        }
                    }
                    if (channel4.temp_history[res2.ts]===undefined||!channel4.temp_history[res2.ts])
                    {
                       channel4.temp_history[res2.ts]=true;
                       channel4.history.push(res2);
                    }
                    else
                    {
                        if (res2.num_channel==2)
                        {
                            channel4.history.push(res2);
                        }
                    }
                    if (res1.ts>=dev.last_data_ts&&res1.ts.toString().length<=13)
                    {
                        dev.last_data_ts=res1.ts;
                    }
                }
            }
            else if (dev.device_type==30) //m-bus-x
            {
                if (newData.type_package==1)
                {
                    var res  = new cell_history(json,newData,1,dev.device_type,dev.version);
                    for (var key in this.devices_list[index].channels)
                    {
                        var channel = this.devices_list[index].channels[key];
                        if (res.address!==undefined)
                        {
                            var validCurrentChannel = res.address.toLowerCase()==channel.mac.toLowerCase();
                            if (validCurrentChannel)
                            {
                                channel.history.push(res);
                            }
                        }
                    }
                }
            }
            else
            {
                if (newData.type_package==1)
                {
                    for (var key in this.devices_list[index].channels)
                    {
                        try
                        {
                            var res  = new cell_history(json,newData,(parseInt(key)+1),this.devices_list[index].device_type,this.devices_list[index].version);
                            if (res)
                            {
                                var channel = this.devices_list[index].channels[key];
                                if (res.time!=undefined)
                                {
                                    var validDateInit = !channel.date_installation||res.time>moment(channel.date_installation).startOf('day' ).unix();
                                    if (validDateInit)
                                    {
                                        if (channel.temp_history === undefined) channel.temp_history = new Object();
                                        if (channel.temp_history[res.time]===undefined||!channel.temp_history[res.time])
                                        {
                                           channel.temp_history[res.time]=true;
                                           channel.history.push(res);
                                        }
                                        else
                                        {
                                            if (channel.type_channel==6)
                                            {
                                                channel.history.push(res);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    channel.history.push(res);
                                }
                                if (res.ts>=this.devices_list[index].last_data_ts&&res.ts.toString().length<=13)
                                {
                                    this.devices_list[index].last_data_ts=res.ts;
                                    if (res.charge)
                                    {
                                        this.devices_list[index].last_data_charge = res.charge;
                                        channel.last_data_charge = res.charge;
                                    }
                                }
                            }
                        }
                        catch(err)
                        {
                            console.log(err);
                        }
                    }
                    return newData;
                }
                else if (newData.type_package==2)
                {
                    for (var key in this.devices_list[index].channels)
                    {
                        try
                        {
                           var res  = new cell_history(json,newData,(parseInt(key)+1),this.devices_list[index].device_type,this.devices_list[index].version);
                            if (res)
                            {
                                if (this.devices_list[index].channels[key].temp_history === undefined) this.devices_list[index].channels[key].temp_history = {};
                                if (res.time!==undefined)
                                {
                                    if (this.devices_list[index].channels[key].temp_history[res.time]===undefined||!this.devices_list[index].channels[key].temp_history[res.time])
                                    {
                                        var si12 = dev.device_type==2;
                                        if(si12)
                                        {
                                            var dangerChannel = this.devices_list[index].channels[key].type_channel == 6;
                                            if(dangerChannel && this.devices_list[index].channels[key].num_channel == res.num_channel )
                                            {
                                                this.devices_list[index].channels[key].temp_history[res.time]=true;
                                                this.devices_list[index].channels[key].history.push(res);
                                            }
                                        }
                                        else
                                        {
                                            this.devices_list[index].channels[key].temp_history[res.time]=true;
                                            this.devices_list[index].channels[key].history.push(res);
                                        }
                                    }
                                }
                                else
                                {
                                    var num = parseInt(key);
                                    var validNum = !isNaN(num)&&num+1==newData.num_channel;
                                    if (validNum)
                                    {
                                        this.devices_list[index].channels[key].history.push(res);
                                    }
                                }
                                if (res.ts>=this.devices_list[index].last_data_ts&&res.ts.toString().length<=13)
                                {
                                    this.devices_list[index].last_data_ts=res.ts;
                                    if (res.charge)
                                    {
                                        this.devices_list[index].last_data_charge = res.charge;
                                        this.devices_list[index].channels[key].last_data_charge = res.charge;
                                    }
                                }
                            }
                        }
                        catch(err)
                        {
                            console.log(err);
                        }
                    }
                    return newData;
                }
                else if (newData.type_package==3)
                {
        //            for (var key in newData.archive)
        //            {
        //                newData.sensors['sensor_'+(newData.num_channel)]=newData.archive[key][0];
        //                newData.time=newData.archive[key][1];
        //                try
        //                {
        //                    var res  = new cell_history(json,newData,newData.num_channel,this.devices_list[index].device_type);
        //                    if (res)
        //                    {
        //                        if (res.time!=undefined)
        //                        {
        //                            if (this.devices_list[index].channels[newData.num_channel].temp_history===undefined)
        //                            {
        //                                this.devices_list[index].channels[newData.num_channel].temp_history = new Object();
        //                            }
        //                            if (this.devices_list[index].channels[newData.num_channel].temp_history[res.time]===undefined||!this.devices_list[index].channels[newData.num_channel].temp_history[res.time])
        //                            {
        //                               this.devices_list[index].channels[newData.num_channel].temp_history[res.time]=true;
        //                               this.devices_list[index].channels[newData.num_channel].history.push(res);
        //                            }
        //                        }
        //                        else
        //                        {
        //                            this.devices_list[index].channels[newData.num_channel].history.push(res);
        //                        }
        //                    }
        //                }
        //                   catch(err)
        //                {
        //                    console.log(err);
        //                }
        //            }
        //            return newData;
                    return false;
                }
                else
                {
                    return false;
                }
            }
        }
        else
        {
            return false;
        }
        
    }
    add_history_multi_new(json,index,date,newData)
    {
        var ts = json.ts;
        for (var key in this.devices_list[index].channels)
        {
            var channel = this.devices_list[index].channels[key];
            var dev = channel._self;
            var date_installation = channel.date_installation?parseInt(moment(channel.date_installation).startOf('day' ).format('x' )):0;
            var validDateInit = !date_installation||ts>date_installation;
            if( validDateInit )
            {
                var res  = new cell_history(json,newData,(parseInt(key)+1),this.devices_list[index].device_type,this.devices_list[index].version);
                var ia;
                if (res.address!==undefined) ia = parseInt(res.address,16);
                var validIa = !isNaN(ia)&&ia==channel.ia;
                if (res.ts>=this.devices_list[index].last_data_ts&&res.ts.toString().length<=13)
                {
                    this.devices_list[index].last_data_ts=res.ts;
                    if (res.charge)
                    {
                        this.devices_list[index].last_data_charge = res.charge;
                    }
                }
                if ( dev.device_type==3 && (newData.type_package==4||newData.type_package==6) )
                {
                    if(validIa) channel.history.push(res);
                }
                else channel.history.push(res);
            }
        }
    }
    add_history_multi_thermo(json,index,date,newData)
    {
        var dev = this.devices_list[index];
        var res  = new cell_history(json,newData,0,dev.device_type,dev.version);
        if (res.ts>=dev.last_data_ts&&res.ts.toString().length<=13)
        {
            dev.last_data_ts=res.ts;
        }
        if(dev.global_history == undefined) dev.global_history = [];
        dev.global_history.push(res);
        for (var key in dev.channels)
        {
            var channel = dev.channels[key];
            channel.history = dev.global_history;
        }
    }
    add_history_single(json,index,date,newData)
    {
        var channel = this.devices_list[index].channels[0];
        var res  = new cell_history(json,newData,1,this.devices_list[index].device_type,this.devices_list[index].version);
        if (res.ts>=this.devices_list[index].last_data_ts&&res.ts.toString().length<=13)
        {
            this.devices_list[index].last_data_ts=res.ts;
            if (res.charge)
            {
                this.devices_list[index].last_data_charge = res.charge;
            }
        }
        this.devices_list[index].channels[0].history.push(res);
        var port5 = json.port === 5;
        var type8 = newData.type_package == 8;
        var type13 = newData.type_package == 13;
        var type14 = newData.type_package == 14;
        var type15 = newData.type_package == 15;
        var type33 = newData.type_package == 33;
        if(port5 && this.devices_list[index].device_type == 24)
        {
            if(type8)
            {
                var validTariffSchedule = isObject(channel.tariff_schedule)&&isObject(channel.tariff_schedule.request);
                if(validTariffSchedule)
                {
                    if(channel.tariff_schedule.request.uuid == res.UUID)
                    {
                        channel.tariff_schedule.response = {
                            result: res,
                            reset: function()
                            {
                                this.edit = cloneObject(this.result);
                            } 
                        };
                        channel.tariff_schedule.response.reset();
                    }
                }
            }
            if(type13||type14)
            {
                var validIndication = isObject(channel.indication)&&isObject(channel.indication.request);
                if( validIndication && channel.indication.request.uuid == res.UUID )
                {
                    if(!isObject(channel.indication.response)) 
                    {
                        channel.indication.response = {
                            block1:{},
                            block2:{},
                            reset: function()
                            {
                                var block1 = cloneObject(this.block1);
                                var block2 = cloneObject(this.block2);
                                this.edit = {};
                                var edit = this.edit;
                                for(var key in block1)
                                {
                                    if( block1[key] !== undefined ) edit[key] = block1[key];
                                }
                                for(var key in block2)
                                {
                                    if( block2[key] !== undefined ) edit[key] = block2[key];
                                }
                            }
                        };
                    }
                    if(type13)
                    {
                        channel.indication.response.block1 = res;
                    }
                    else if(type14)
                    {
                        channel.indication.response.block2 = res;
                    }
                    channel.indication.response.reset();
                }
            }
            if(type15||type33)
            {
                var validSpecialDays = isObject(channel.special_days)&&isObject(channel.special_days.request);
                if( validSpecialDays && channel.special_days.request.uuid == res.UUID )
                {
                    if(!isObject(channel.special_days.response)) 
                    {
                        channel.special_days.response = {
                            block1:{},
                            block2:{},
                            reset: function()
                            {
                                var block1 = cloneObject(this.block1);
                                var block2 = cloneObject(this.block2);
                                this.edit = {};
                                var edit = this.edit;
                                for(var key in block1)
                                {
                                    if( block1[key] !== undefined ) edit[key] = block1[key];
                                }
                                for(var key in block2)
                                {
                                    if( block2[key] !== undefined ) edit[key] = block2[key];
                                }
                            }
                        };
                    }
                    if(type15)
                    {
                        channel.special_days.response.block1 = res;
                    }
                    else if(type33)
                    {
                        channel.special_days.response.block2 = res;
                    }
                    channel.special_days.response.reset();
                }
            }
        } 
    }
    add_history(json,index,date,keys)
    {   
        var device = this.devices_list[index];
        if (json.ts>=device.last_data_ts&&json.ts.toString().length<=13)
        {
            this.devices_list[index].last_data_ts=json.ts;
        }
        if (device&&device.device_type)
        {
            var newData = new Parser(device.device_type,json.data,json.port,device.version,keys);
            
            // if(json.fcnt == 260) 
            // {
            //     console.log('Когда только распарсили пакет',newData.reason);
            // }

            if (newData.validParse)
            {
                switch (newData.device_type) {
                    case 1:
                        this.add_history_multi_new(json,index,date,newData);
                        break;
                    case 2:
                        this.add_history_multi_new(json,index,date,newData);
                        break;
                    case 3:
                        this.add_history_multi_new(json,index,date,newData);
                        break;
                    case 4:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 5:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 9:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 6:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 7:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 8:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 10:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 11:
                        this.add_history_multi_new(json,index,date,newData);
                        break;
                    case 12:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 13:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 14:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 15:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 17:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 18:
                        this.add_history_multi_new(json,index,date,newData);
                        break;
                    case 20:
                        this.add_history_multi_new(json,index,date,newData);
                        break;
                    case 21:
                        this.add_history_multi_new(json,index,date,newData);
                        break;
                    case 23:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 24:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 25:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 26:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 27:
                        this.add_history_single(json,index,date,newData);
                        break;
                    case 28:
                        this.add_history_multi_new(json,index,date,newData);
                        break;
                    case 30:
                        this.add_history_multi_thermo(json,index,date,newData);
                        break;
                    case 31:
                        this.add_history_single(json,index,date,newData);
                        break;
                    default:
                        return false;
                        break;
                }
            }
            else
            {
                return false;
            }
            return newData;
        }
        else
        {
            return false;
        }
    };
    channels_search(num_channel,devEui,level_1,level_2)
    {
        for (var i=0;i< this.devices_list.length;i++)
        {
            if (this.devices_list[i].devEui==devEui)
            {
                for (var j=0;j< this.devices_list[i].channels.length;j++)
                {
                    if (this.devices_list[i].channels[j].address_level_1==level_1.address_level_1&&this.devices_list[i].channels[j].name_level_1==level_1.name_level_1&&this.devices_list[i].channels[j].level_2==level_2&&this.devices_list[i].channels[j].num_channel==num_channel)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    };
    device_search(devEui,level_1,level_2)
    {
        for (var i=0;i< this.devices_list.length;i++)
        {
            for (var j=0;j< this.devices_list[i].channels.length;j++)
            {
                if (this.devices_list[i].channels[j].name_level_1==level_1.name_level_1&&this.devices_list[i].channels[j].address_level_1==level_1.address_level_1&&this.devices_list[i].channels[j].level_2==level_2)
                {
                    return true;
                }
            }
        }
        return false;
    };
    level_2_search(level_2,level_1)
    {
        for (var i=0;i< this.devices_list.length;i++)
        {
            for (var j=0;j< this.devices_list[i].channels.length;j++)
            {
                if (this.devices_list[i].channels[j].name_level_1==level_1.name_level_1&&this.devices_list[i].channels[j].address_level_1==level_1.address_level_1&&this.devices_list[i].channels[j].level_2==level_2)
                {
                    return this.devices_list[i].channels[j];
                }
            }
        }
        return false;
    };
    level_1_search(name,address)
    {
        for (var i=0;i< this.devices_list.length;i++)
        {
            for (var j=0;j< this.devices_list[i].channels.length;j++)
            {
                if (this.devices_list[i].channels[j].name_level_1==name&&this.devices_list[i].channels[j].address_level_1==address)
                {
                    return this.devices_list[i].channels[j];
                }
            }
        }
        return false;
    };
    search_channel_device_list(num,devEui)
    {
        num--;
        for (var i=0;i< this.devices_list.length;i++)
        {
                if (devEui==this.devices_list[i].devEui&&this.devices_list[i].channels[num]!=undefined&&this.devices_list[i].channels[num].status!=undefined&&this.devices_list[i].channels[num].status)
                {
                   return true;
                }
        }
        return false;
    };
    select_channel(devEui,num_channel)
    {
        try
        {
            for (var i=0;i< this.devices_list.length;i++)
            {
                if (this.devices_list[i].devEui==devEui)
                {
                    for (var j=0;j< this.devices_list[i].channels.length;j++)
                    {
                        if (this.devices_list[i].channels[j].num_channel==num_channel)
                        {
                            this.select_device_devEui=devEui;
                            this.select_device_channel=num_channel;
                            this.select_channel_temp = this.devices_list[i].channels[j];
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        catch(err)
        {
            return false; 
        }
    }
    get_active_channel(devEui)
   {
       var channels = this.get_device(devEui).channels;
       var resArr = [];
       if (channels)
       {
            for (var i =0;i<channels.length;i++)
            {
                if (channels[i].status!=undefined&&channels[i].status==1)
                {
                    resArr.push(channels[i].name);
                }
            }
       }
       return resArr;
   };
    get_device(devEui)
   {
       for (var i = 0; i<this.devices_list.length;i++)
       {
           if (this.devices_list[i].devEui==devEui)
           {
               return this.devices_list[i];
           }
       }
       return false;
   }
   reconnect_device(device)
   {
       for (var i = 0; i<this.devices_list.length;i++)
       {
           if (this.devices_list[i].devEui==device.devEui)
           {
               this.devices_list[i]=Object.assign(this.devices_list[i],device);
               return true;
           }
       }
       return false;
   }
   clean_tick_device_original()
   {
       for (var i = 0; i<this.full_devices_list.length;i++)
       {
            this.full_devices_list[i].tick=false;
       }
   }
   get_device_original(devEui)
   {
       for (var i = 0; i<this.full_devices_list.length;i++)
       {
           if (this.full_devices_list[i].devEui==devEui)
           {
               return this.full_devices_list[i];
           }
       }
       return undefined;
   }
   get_count_channel()
   {
       var count_channel=0;
       for (var i = 0; i< this.devices_list.length;i++)
       {
           for (var j = 0 ; j<this.devices_list[i].channels.length;j++)
           {
               if (this.devices_list[i].channels[j].type_channel != undefined && this.devices_list[i].channels[j].num_channel !=undefined)
               {
                   count_channel++
               }
           }
       }
       return count_channel;
   }
   get_channel(devEui,channel)
   {
       try
       {
            for (var i = 0; i<this.devices_list.length;i++)
            {
                if (this.devices_list[i].devEui==devEui)
                {
                     for (var j = 0; j<this.devices_list[i].channels.length;j++)
                     {
                         if (this.devices_list[i].channels[j].num_channel==channel)
                         {
                             return this.devices_list[i].channels[j];
                         }
                     }
                }
            }
        }
        catch (err)
        {
            return [];
        }
        return new Object();
   }
   get_select_channel()
   {
       try
       {
            for (var i = 0; i<this.devices_list.length;i++)
            {
                if (this.devices_list[i].devEui==this.select_device_devEui)
                {
                     for (var j = 0; j<this.devices_list[i].channels.length;j++)
                     {
                         if (this.devices_list[i].channels[j].num_channel==this.select_device_channel)
                         {
                             return this.devices_list[i].channels[j];
                         }
                     }
                }
            }
        }
        catch (err)
        {
            return [];
        }
   }
   get_history(channel,date)
   {
       try
       {
        var history = channel.history;
        var temp = new Array();
        var dev = this.get_device(channel.devEui);
        var dt = 0;
        if (dev) dt = dev.device_type;
        for (var i = 0; i <history.length;i++)
        {
            var validTs = history[i].ts !== undefined && history[i].ts>date.getStart()*1000&&history[i].ts<date.getEnd()*1000;
            var validTime = history[i].time !== undefined && history[i].time>=date.getStart()&&history[i].time<=date.getEnd();
            var ss = channel.type_channel==13;
            var ss0102 = channel.type_channel==31;
            var smart_type_channel = (channel.type_channel==10||channel.type_channel==11||channel.type_channel==12||ss)&&dev.version == 0;
            var smartRev2_type_channel = (channel.type_channel==10||ss0102||channel.type_channel==11||channel.type_channel==12)&&dev.version >= 1;
            var hs = channel.type_channel==23;
            var um = channel.type_channel==25;
            var si13 = dt == 3;
            var si13_modBus = si13 && channel.type_channel == 22 && dev.version > 0;
            var si13_m = si13 && channel.type_channel == 16 && dev.version == 0;
            var si13_m_rev2 = si13 && channel.type_channel == 16 && dev.version == 1;
            var si13_danger = si13 && channel.type_channel == 6 && dev.version == 0;
            var si13_danger_rev2 = si13 && channel.type_channel == 6 && dev.version == 1;
            var si21 = dt == 11;
            var si22 = dt == 18;
            var si21_22rev2 = ( si21 || si22 ) && dev.version > 0 && dev.version < 2;
            var si21_22rev3 = ( si21 || si22 ) && dev.version >= 2;
            var thermo = dt == 30;
            if(si13)
            {
                if(si13_m&&validTs)
                {
                    temp.push(history[i]);
                }
                else if (si13_m_rev2&&validTime)
                {
                    temp.push(history[i]);
                } 
                else if(si13_danger&&validTs)
                {
                    temp.push(history[i]);
                }
                else if(si13_danger_rev2&&validTime)
                {
                    temp.push(history[i]);
                }
                else if(si13_modBus && validTime)
                {
                    temp.push(history[i]);
                }
                else if (validTs)
                {
                    temp.push(history[i]);
                }
            }
            else if (channel.type_channel==7||channel.type_channel==9||smart_type_channel)
            {
                if (history[i].ts>date.getStart()*1000&&history[i].ts<date.getEnd()*1000)
                {
                    temp.push(history[i]);
                }
            }
            else if ( channel.type_channel==6 && ( dt == 20 || dt == 21 ) )
            {
                if (history[i].ts>date.getStart()*1000&&history[i].ts<date.getEnd()*1000)
                {
                    temp.push(history[i]);
                } 
            }
            else if ((channel.type_channel==8||channel.type_channel==6||smartRev2_type_channel || hs || um) && !si13)
            {
                if( ( si21_22rev2 || si21_22rev3 ) && ( validTs || validTime ) )
                {
                    temp.push(history[i]);
                } 
                else if (validTime)
                {
                    temp.push(history[i]);
                } 
            }
            else
            {  
                if ( dt == 20 || dt == 21 )
                {
                    if (history[i].ts>date.getStart()*1000&&history[i].ts<date.getEnd()*1000)
                    {
                        temp.push(history[i]);
                    }
                }
                else if (dt == 12 )
                {
                    var validTime = history[i].time>=date.getStart()&&history[i].time<=date.getEnd();
                    var validDate1 = history[i].date_1&&history[i].date_1>date.getStart()&&history[i].date_1<date.getEnd();
                    var validDate1 = history[i].date_2&&history[i].date_2>date.getStart()&&history[i].date_2<date.getEnd();
                    if (validTime||validDate1||validDate1)
                    {
                        if (history[i].type!=5||(validDate1&&history[i].type==5))
                        {
                            temp.push(history[i]);
                        }
                    }
                }
                else if ( dt == 27 )
                {
                    var validTime = history[i].time>=date.getStart()&&history[i].time<=date.getEnd();
                    var validDate1 = history[i].date_1&&history[i].date_1>date.getStart()&&history[i].date_1<date.getEnd();
                    var validDate1 = history[i].date_2&&history[i].date_2>date.getStart()&&history[i].date_2<date.getEnd();
                    if (validTime||validDate1||validDate1)
                    {
                        if (history[i].type!=5||(validDate1&&history[i].type==5))
                        {
                            temp.push(history[i]);
                        }
                    }
                }
                // else if ( dt == 24 )
                // {
                //     var validTime = history[i].time>date.getStart()&&history[i].time<date.getEnd();
                //     var validDate1 = history[i].date_1&&history[i].date_1>date.getStart()&&history[i].date_1<date.getEnd();
                //     var validDate1 = history[i].date_2&&history[i].date_2>date.getStart()&&history[i].date_2<date.getEnd();
                //     if (validTime||validDate1||validDate1||history[i].time==undefined)
                //     {
                //         if (history[i].type!=5||(validDate1&&history[i].type==5))
                //         {
                //             temp.push(history[i]);
                //         }
                //     }
                // }
                else if (history[i].time>=date.getStart()&&history[i].time<=date.getEnd())
                {
                    temp.push(history[i]);
                } 
            }
        }
        return temp;
       }
       catch(err)
       {
           return []
       }
   }

   get_history_select_channel(date)
   {
        var channel = this.get_select_channel()
        return this.get_history(channel,date);    
   }
   get_history_last(history)
   {
       try
       {
            var temp = new Object();
            temp.time = 0;
            temp.index = 0;
            for (var i = 0;i<history.length ;i++)
            {
                if (history[i].time>temp.time) 
                {
                    temp.time = history[i].time;
                    temp.index = i;
                }
            }
            return history[temp.index];
        }
        catch (err)
        {
            return new cell_history();
        }
   }
   //получение статистики
   get_statistics(date)
   {
       this.reload_all_channel_list();
       try
        { 
            var device = this.get_device(this.select_device_devEui);
            var channel = this.get_channel(this.select_device_devEui,this.select_device_channel);
            var minDate = 99999999999999;
            var maxDate = 0;
            var minS = undefined;
            var maxS = undefined;
            var fcnt = 0;
            var snr = new Object();
            snr.val = 0;
            snr.count = 0;
            var rssi = new Object();
            rssi.val = 0;
            rssi.count=0;
            var _dangers = new Object();
            var connect = [];
            var arr_date = [];
            var arr_rssi = [];
            var arr_snr = [];
            var tempArr  = new Array();
            var arr_value = [];
            var arr_value_4 = [];
            var temp = new Object();
            var my_converter = new vega_converter();
            channel.statistics.last_coordinate = {
                time:0
            };
            channel.statistics.arr_valid_coordinates = [];
            channel.statistics.count = 0;
            channel.statistics.countPackage_type_1 = 0;
            channel.statistics.countPackage_type_2 = 0;
            channel.statistics.countPackage_type_3 = 0;
            channel.statistics.countPackage_type_4 = 0;
            channel.statistics.countPackage_type_5 = 0;
            channel.statistics.countPackage_type_6 = 0;
            channel.statistics.countPackage_type_9 = 0;
            channel.statistics.count_1 = 0;
            channel.statistics.count_all = 0;
            channel.statistics.count_full = 0;
            channel.statistics.count_danger = 0;
            channel.statistics.count_danger_full = 0;
            channel.statistics.chart = new Array();
            channel.statistics.chart_consumption = new Array();
            channel.statistics.chart_t = new Array();
            channel.statistics.arr_value_consum = new Array();
            channel.statistics.arr_value_consum_v4 = new Array();
            channel.statistics.arr_value_events = new Array();
            channel.statistics.chart_temperature = new Array();
            channel.statistics.chart_temperature_new = new Array();
            channel.statistics.chart_sensor_new = new Array();


            
            channel.statistics.chart_damp_new = new Array();
            channel.statistics.chart_lux_new = new Array();
            channel.statistics.chart_dB_new = new Array();
            channel.statistics.chart_CO2_new = new Array();


            channel.statistics.last_ts=0;
            channel.statistics.last_time=0;
            channel.statistics.arr_power_profile = [];
            var valid = new valid_data();
            var kt = this.select_channel_temp.kt;
            kt = valid.isNumber(kt)?kt:1;
            var arr_ts_list = [];
            var summ_t=0;
            var count_t=0;
            var _items = new Object();
            var _items_1 = new Object();
            var _items_counter_all = new Object();
            var _items_counter = new Object();
            var _items_counter_power = new Object();
            var _items_counter_2 = new Object();
            var _items_counter_p_2 = new Object();
            var _items_all = new Object();
            var last_type_1 = {ts:null,time:null,value:null};
            var last_type_5 = {ts:null,time:null,value:null};
            var last_sensor_out_1 = {ts:null,time:null,value:null};
            var last_sensor_out_2 = {ts:null,time:null,value:null};
            var last_state_energy = {ts:null,time:null,value:null};
            
            var last_charge = {ts:null,time:null,value:null};
            var last_charge = {ts:null,time:null,value:null};
            var summ_sensorTP = 0;
            var count_sensorTP = 0;

            var currentVersion = parseInt(device.version);

            var si11 = device.device_type == 1;
            var si21 = device.device_type == 11;
            var si22 = device.device_type == 18;
            var si12 = device.device_type == 2;
            var si11rev2 = si11 && currentVersion >= 2;
            var si12rev2 = si12 && currentVersion >= 2;
            var si21_22rev3 = (si21||si22) && currentVersion >= 2;
            var ss0102 = device.device_type == 31;
            var impulse = channel.type_channel >= 1 && channel.type_channel<=5;
            var channelDanger = channel.type_channel==6;
            var si13 = device.device_type == 3 && device.version == 0;
            var si13rev2 = device.device_type == 3 && device.version == 1;
            var smart = (device.device_type == 10 || device.device_type == 8 || device.device_type == 7 || device.device_type == 6)&&device.version == 0;
            var hs = device.device_type == 23;
            var um = device.device_type == 25;
            var smartRev2 = ( device.device_type == 8 || device.device_type == 7 || device.device_type == 6 || device.device_type == 31)&&device.version >= 1;
            var td11 =  device.device_type == 4 && device.version == 0;
            var td11rev2 =  device.device_type == 4 && device.version == 1;
            var tp11 = device.device_type == 5 && device.version == 0;
            var tp11rev2 = device.device_type == 5 && device.version == 1;
            var mbus1 = device.device_type == 20;
            var thermo = device.device_type == 30;
            var mbus2 = device.device_type == 21;
            var mbus = mbus1 || mbus2;
            var gm2 = device.device_type == 13;
            var gm1 = device.device_type == 17;
            var sve = device.device_type == 9;
            var tl11 = device.device_type == 15;
            var lm11 = device.device_type == 14;
            var src = device.device_type == 26;
            var ue = device.device_type == 12;
            var ue_merc = device.device_type == 27;
            var ue_spbzip = device.device_type == 24 ;
            var sh02rev2 = device.device_type == 28 && device.version >= 1;
            var sh02rev3 = device.device_type == 28 && device.version >= 2;
            var sh02 = device.device_type == 28 && !sh02rev2;
           

            var tz = get_time_zone();
            for (var i = 0; i< channel.history.length;i++)
            {
                var cell_history = channel.history[i];
                if( device.version != channel.history[i].version ) continue;
                var validHistory = channel.history[i] !== undefined;
                if (td11rev2&&validHistory)
                {
                    tz = get_time_zone() * 1000;
                    // td11
                    var checkEvent = cell_history.reason!==0;
                    var port = cell_history.port;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var validType = cell_history.type == 1;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    if ( port == 2 )
                    {
                        if ( correctTime && validType )
                        {
                            var timeMs = cell_history.time * 1000;
                            var _item = [cell_history.time,1,0];
                            if (cell_history.time > channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_fcnt=cell_history.fcnt; 
                                channel.statistics.last_hall_1 = cell_history.hall_1;  
                                channel.statistics.last_hall_2 = cell_history.hall_2;  
                                channel.statistics.last_state_security = cell_history.state_security;  
                                channel.statistics.last_state_tamper = cell_history.state_tamper;  
                                channel.statistics.last_limit_exceeded = cell_history.limit_exceeded;
                                channel.statistics.last_min_temperature = cell_history.min_temperature;
                                channel.statistics.last_max_temperature = cell_history.max_temperature;
                            }
                            if ((checkEvent||cell_history.limit_exceeded)&&!_dangers[timeMs])
                            {
                                _dangers[timeMs]=true;
                                channel.statistics.count_danger++;
                                if (checkEvent)
                                {
                                    _item[2] = 1;
                                    _item[3] = cell_history.reason;
                                }
                                if (cell_history.limit_exceeded)
                                {
                                    _item[2] = 2;
                                    _item[3] = cell_history.reason;
                                }
                                if (cell_history.limit_exceeded&&checkEvent)
                                {
                                    _item[2] = 3;
                                    _item[3] = cell_history.reason;
                                }
                            }
                            if (!_items[timeMs])
                            {
                                if (!isNaN(cell_history.temperature))
                                {
                                    summ_t += cell_history.temperature;
                                    count_t++;
                                }
                                channel.statistics.count++;
                                _items[timeMs]=true;
                                channel.statistics.chart_temperature_new.push( [timeMs+tz,cell_history.temperature,cell_history.min_temperature,cell_history.max_temperature, cell_history.limit_exceeded]);
                                arr_value_4.push(_item);
                                channel.statistics.chart_temperature.push( [timeMs, cell_history.temperature] );
                            }
                        }
                    }
                }
                else if ( td11 )
                {
                    //td11
                    var checkEvent = cell_history.reason!==0;
                    var t = parseFloat(cell_history.temperature);
                    var _item = [cell_history.ts,1,0];
                    var t_max = channel.max_t;
                    var t_min = channel.min_t;
                    var checkTemperature = t<=t_min||t>=t_max;
                    var validTs = cell_history.ts!==undefined&&cell_history.ts>0;
                    var validType = cell_history.type == 1;
                    var correctTs = validTs&&cell_history.ts>=(date.getStart()*1000)&&cell_history.ts<=(date.getEnd()*1000);
                    var port = cell_history.port;
                    if ( correctTs && validType &&  port == 2)
                    {
                        if ( cell_history.ts > channel.statistics.last_ts )
                        {
                            channel.statistics.last_temperature=cell_history.temperature;
                            channel.statistics.last_charge=cell_history.charge;
                            channel.statistics.last_time=cell_history.time;
                            channel.statistics.last_fcnt=cell_history.fcnt; 
                            channel.statistics.last_hall_1 = cell_history.hall_1;  
                            channel.statistics.last_hall_2 = cell_history.hall_2;  
                            channel.statistics.last_state_security = cell_history.state_security;  
                            channel.statistics.last_state_tamper = cell_history.state_tamper;  
                            channel.statistics.last_limit_exceeded = cell_history.limit_exceeded;
                            channel.statistics.last_min_temperature = cell_history.min_temperature;
                            channel.statistics.last_max_temperature = cell_history.max_temperature;
                            channel.statistics.last_ts=cell_history.ts;
                        }
                        if ((checkEvent||checkTemperature)&&!_dangers[cell_history.ts])
                        {
                            _dangers[cell_history.ts]=true;
                            channel.statistics.count_danger++;
                            if (checkEvent)
                            {
                                _item[2] = 1;
                                _item[3] = cell_history.reason;
                            }
                            if (checkTemperature)
                            {
                                _item[2] = 2;
                                _item[3] = cell_history.reason;
                            }
                            if (checkTemperature&&checkEvent)
                            {
                                _item[2] = 3;
                                _item[3] = cell_history.reason;
                            }
                        }
                        if (!_items[cell_history.ts])
                        {
                            channel.statistics.count++;
                            _items[cell_history.ts]=true;
                            arr_value_4.push(_item);
                            if (!isNaN(cell_history.temperature))
                            {
                                summ_t += cell_history.temperature;
                                count_t++;
                            }
                        }
                    }
                }
                else if ( sve )
                {
                    //sve
                    var port = cell_history.port;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var validType = cell_history.type == 1;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    if( validType && validTime )
                    {
                        if (correctTime)
                        {
                            var _item = [cell_history.time,1,0];
                            var checkEvent = cell_history.state_display||cell_history.leaking||cell_history.breakthrough||cell_history.hall_1;
                            if (checkEvent&&!_dangers[cell_history.time])
                            {
                                _dangers[cell_history.time]=true;
                                channel.statistics.count_danger++;
                                _item[2] = 1;
                                _item[3] = 'danger';
                            }
                            if (!_items[cell_history.time])
                            {
                                channel.statistics.count++;
                                _items[cell_history.time]=true;
                                arr_value_4.push(_item);
                            }
                        }
                        if (cell_history.time>channel.statistics.last_time)
                        {
                            channel.statistics.last_temperature=cell_history.temperature;
                            channel.statistics.last_charge=cell_history.charge;
                            channel.statistics.last_time=cell_history.time;
                            channel.statistics.last_fcnt=cell_history.fcnt; 
                            channel.statistics.last_hall_1 = cell_history.hall_1;  
                            channel.statistics.last_sensorKB = cell_history.sensorKB;
                            channel.statistics.last_state_display=cell_history.state_display;
                            channel.statistics.last_leaking = cell_history.leaking;
                            channel.statistics.last_breakthrough = cell_history.breakthrough;
                        }
                    }
                }
                else if (tl11)
                {
                    //tl11
                    var port = cell_history.port;
                    if (cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd()&&port==2)
                    {
                        var timeMs = cell_history.time*1000;
                        var _item = [timeMs,1,0];
                        channel.statistics.count_all++;
                        _items_all[timeMs]=true;
                        var t_max = channel.max_t;
                        var t_min = channel.min_t;
                        var t = parseFloat(cell_history.temperature);
                        var t2 = parseFloat(cell_history.temperature_2);
                        
                        var checkTemperature_1 = t<=t_min||t>=t_max; //5
                        var checkTemperature_2 = t2<=t_min||t2>=t_max; //6
                        var normReason = cell_history.reason=='00';
                        
                        if (checkTemperature_1||checkTemperature_2||!normReason)
                        {
                            _item[1]=parseInt(cell_history.reason);
                            _item[2]=1;
                            
                            
                            var event = new Object();
                            event.time = cell_history.time;
                            event.reason = cell_history.reason;
                            event.deviation = '';
                            if (checkTemperature_1)
                            {
                                event.deviation+='Температура 1'+', ';
                            }
                            if (checkTemperature_2)
                            {
                                event.deviation+='Температура 2'+', ';
                            }
                            if (!normReason)
                            {
                                event.deviation+='Незапланированное событие'+', ';
                            }
                            if (event.deviation.length>0)
                            {
                                event.deviation = event.deviation.slice(0,event.deviation.length-2);
                            }
                            event.temperature_1 = t;
                            event.temperature_2 = t2;
                            event.fcnt = cell_history.fcnt;
                            event.get_time = cell_history.get_time;
                            channel.statistics.arr_value_events.push(event);
                        }
                        
                        if (cell_history.time>channel.statistics.last_time)
                        {
                            channel.statistics.last_temperature=cell_history.temperature;
                            channel.statistics.last_temperature_2=cell_history.temperature_2;
                            channel.statistics.last_charge=cell_history.charge;
                            channel.statistics.last_time=cell_history.time;
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_fcnt=cell_history.fcnt;
                            channel.statistics.last_hall_1 = cell_history.hall_1;  
                            channel.statistics.last_hall_2 = cell_history.hall_2;  
                            channel.statistics.last_state_tamper = cell_history.state_tamper;  
                        }
                        channel.statistics.chart_t.push( [timeMs,cell_history.temperature,cell_history.temperature_2]);
                        arr_value_4.push(_item);
                    }
                }
                else if (gm2)
                {
                    //УГ
                    var port = cell_history.port;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                    if (port == 2)
                    {
                        if (correctTime&&!_items_counter[cell_history.time])
                        {
                            var _item = [cell_history.time,1,0];
                            _items_counter[cell_history.time]=true;
                            var reason = cell_history.reason;
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_fcnt=cell_history.fcnt;
                                channel.statistics.last_sensor_rate_sum=cell_history.sensor_rate_sum;
                                channel.statistics.last_sensor_in_1=cell_history.sensor_in_1;
                                channel.statistics.last_sensor_in_2=cell_history.sensor_in_2;
                                channel.statistics.last_sensor_out_1=cell_history.sensor_out_1;
                                channel.statistics.last_sensor_out_2=cell_history.sensor_out_2;
                                channel.statistics.last_hall_1 = cell_history.hall_1;  
                                channel.statistics.last_state_tamper = cell_history.state_tamper;  
                            }
                            if (cell_history.time<minDate)
                            {
                                minDate = cell_history.time;
                                minS = cell_history.sensor_rate_sum;
                            }
                            if (cell_history.time>maxDate)
                            {
                                maxDate = cell_history.time;
                                maxS = cell_history.sensor_rate_sum;
                            }
                            if (reason)
                            {
                                reason = parseInt(reason);
                                if (!isNaN(reason)&&reason>0)
                                {
                                    _item[2]=1;
                                    _item[1] = reason;
                                }
                            }
                            arr_value_4.push(_item);
                            channel.statistics.chart.push( [(cell_history.time+get_time_zone())*1000,cell_history.sensor_rate_sum,reason]);
                            channel.statistics.chart_consumption.push( [(cell_history.time+get_time_zone())*1000,cell_history.sensor_rate_sum,reason,cell_history.fcnt]);
                            
                            channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                        }
                        else if(validTime&&!_items_counter[cell_history.time])
                        {
                            _items_counter[cell_history.time]=true;
                            channel.statistics.chart_consumption.push( [(cell_history.time+get_time_zone())*1000,cell_history.sensor_rate_sum,reason,cell_history.fcnt]);
                        }
                    }
                }
                else if (gm1)
                {
                    //GM-1
                    var port = cell_history.port;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                    var tz = get_time_zone() * 1000;
                    if (port == 2)
                    {
                        var _item = [cell_history.time,1,0];
                        var reason = cell_history.reason;
                        if (cell_history.ts>channel.statistics.last_ts)
                        {
                            channel.statistics.last_ts=cell_history.ts;
                        }
                        if(validTime)
                        {
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_fcnt=cell_history.fcnt;
                                channel.statistics.last_sensor_rate_sum=cell_history.sensor_rate_sum;
                            }
                        }
                        if (correctTime&&!_items_counter[cell_history.time])
                        {
                            var timeMS = cell_history.time * 1000;
                            var time = timeMS + tz;
                            _items_counter[cell_history.time]=true;
                            if (cell_history.time<minDate)
                            {
                                minDate = cell_history.time;
                                minS = cell_history.sensor_rate_sum;
                            }
                            if (cell_history.time>maxDate)
                            {
                                maxDate = cell_history.time;
                                maxS = cell_history.sensor_rate_sum;
                            }
                            if (reason)
                            {
                                reason = parseInt(reason);
                                if (!isNaN(reason)&&reason>0)
                                {
                                    _item[2]=1;
                                    _item[1] = reason;
                                }
                            }
                            arr_value_4.push(_item);
                            channel.statistics.chart.push( [time,cell_history.sensor_rate_sum,reason] );
                            channel.statistics.chart_consumption.push( [time,cell_history.sensor_rate_sum,reason,cell_history.fcnt] );
                            channel.statistics.chart_temperature.push( [timeMS,cell_history.temperature]);
                        }
                        else if(validTime&&!_items_counter[cell_history.time])
                        {
                            _items_counter[cell_history.time]=true;
                            channel.statistics.chart_consumption.push( [time,cell_history.sensor_rate_sum,reason,cell_history.fcnt] );
                        }
                    }
                }
                else if ( lm11 )
                {
                    //lm11
                    var type_package = cell_history.type;
                    var port = cell_history.port;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var _item_counter = [cell_history.time,0,0];
                    if (port == 2 && type_package==1)
                    {
                        if (cell_history.time>=channel.statistics.last_time)
                        {
                            channel.statistics.last_temperature=cell_history.temperature;
                            channel.statistics.last_charge=cell_history.charge;
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_time=cell_history.time;
                            channel.statistics.last_fcnt=cell_history.fcnt;

                            channel.statistics.last_in_move=cell_history.in_move;
                            channel.statistics.last_speed=cell_history.speed;
                            channel.statistics.last_sat_visible=cell_history.sat_visible;
                            channel.statistics.last_sat_used=cell_history.sat_used;
                            channel.statistics.last_alarm=cell_history.alarm;
                            channel.statistics.last_angle=cell_history.angle;
                            
                            channel.statistics.last_lat=cell_history.lat;
                            channel.statistics.last_lng=cell_history.lng;
                        }
                        if (correctTime&&!_items_counter[cell_history.time])
                        {
                            if (cell_history.time>=channel.statistics.last_coordinate.time&&cell_history.coord_status)
                            {
                                channel.statistics.last_coordinate.ts = cell_history.ts;
                                channel.statistics.last_coordinate.time = cell_history.time;
                                channel.statistics.last_coordinate.temperature=cell_history.temperature;
                                channel.statistics.last_coordinate.charge=cell_history.charge;
                                channel.statistics.last_coordinate.fcnt=cell_history.fcnt;
                                channel.statistics.last_coordinate.in_move=cell_history.in_move;
                                channel.statistics.last_coordinate.speed=cell_history.speed;
                                channel.statistics.last_coordinate.sat_visible=cell_history.sat_visible;
                                channel.statistics.last_coordinate.sat_used=cell_history.sat_used;
                                channel.statistics.last_coordinate.alarm=cell_history.alarm;
                                channel.statistics.last_coordinate.lat=cell_history.lat;
                                channel.statistics.last_coordinate.lng=cell_history.lng;
                            }
                            var _item = [cell_history.time,1,0];
                            _items_counter[cell_history.time]=true;
                            
                            if (cell_history.time<minDate)
                            {
                                minDate = cell_history.time;
                            }
                            if (cell_history.time>maxDate)
                            {
                                maxDate = cell_history.time;
                            }
                            if (cell_history.alarm)
                            {
                                _item[2]=1;
                                _item[1] = 1;
                            }
                            if (cell_history.lat&&cell_history.lng) channel.statistics.arr_valid_coordinates[cell_history.time]=cell_history;
                            arr_value_4.push(_item);
                            channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                        }
                    }
                }
                else if ( src )
                {
                    //src
                    var type_package = cell_history.type;
                    var port = cell_history.port;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var _item_counter = [cell_history.time,0,0];
                    if (port == 2)
                    {
                        if (cell_history.time>=channel.statistics.last_time)
                        {
                            channel.statistics.last_temperature=cell_history.temperature;
                            channel.statistics.last_charge=cell_history.charge;
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_time=cell_history.time;
                            channel.statistics.last_fcnt=cell_history.fcnt;
                            channel.statistics.last_status_state=cell_history.status_state;
                            channel.statistics.last_state_tamper=cell_history.state_tamper;
                            channel.statistics.last_led_duty=cell_history.led_duty;
                            channel.statistics.last_nomenal_voltage=cell_history.nomenal_voltage;
                            channel.statistics.last_reason=cell_history.reason;
                            channel.statistics.last_angle=cell_history.angle;
                            channel.statistics.last_nomenal_voltage=cell_history.nomenal_voltage;
                            channel.statistics.last_total_power_summary=cell_history.total_power_summary;
                            channel.statistics.last_lat=cell_history.lat;
                            channel.statistics.last_lng=cell_history.lng;
                        }
                        if (correctTime&&!_items_counter[cell_history.time])
                        {
                            if (cell_history.time>=channel.statistics.last_coordinate.time)
                            {
                                channel.statistics.last_coordinate.temperature=cell_history.temperature;
                                channel.statistics.last_coordinate.charge=cell_history.charge;
                                channel.statistics.last_coordinate.ts=cell_history.ts;
                                channel.statistics.last_coordinate.time=cell_history.time;
                                channel.statistics.last_coordinate.fcnt=cell_history.fcnt;
                                channel.statistics.last_coordinate.status_state=cell_history.status_state;
                                channel.statistics.last_coordinate.state_tamper=cell_history.state_tamper;
                                channel.statistics.last_coordinate.led_duty=cell_history.led_duty;
                                channel.statistics.last_coordinate.nomenal_voltage=cell_history.nomenal_voltage;
                                channel.statistics.last_coordinate.reason=cell_history.reason;
                                channel.statistics.last_coordinate.angle=cell_history.angle;
                                channel.statistics.last_coordinate.nomenal_voltage=cell_history.nomenal_voltage;
                                channel.statistics.last_coordinate.total_power_summary=cell_history.total_power_summary;
                                channel.statistics.last_coordinate.lat=cell_history.lat;
                                channel.statistics.last_coordinate.lng=cell_history.lng;
                            }
                            var _item = [cell_history.time,1,0];
                            _items_counter[cell_history.time]=true;
                            
                            if (cell_history.time<minDate)
                            {
                                minDate = cell_history.time;
                            }
                            if (cell_history.time>maxDate)
                            {
                                maxDate = cell_history.time;
                            }
                            if (cell_history.alarm)
                            {
                                _item[2]=1;
                                _item[1] = 1;
                            }
                            if (cell_history.lat&&cell_history.lng) channel.statistics.arr_valid_coordinates[cell_history.time]=cell_history;
                            arr_value_4.push(_item);
                            channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                        }
                    }
                }
                else if ( ue || ue_merc )
                {
                    //ue
                    var type_package = cell_history.type;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var validDate1 = cell_history.date_1!==undefined&&cell_history.date_1>0;
                    var validDate2 = cell_history.date_2!==undefined&&cell_history.date_2>0;
                    var correctTime = validTime&&(cell_history.time)>=date.getStartUTC()&&(cell_history.time)<=date.getEndUTC();
                    var correctDate1 = validDate1&&(cell_history.date_1)>date.getStartUTC()&&(cell_history.date_1)<date.getEndUTC();
                    var correctDate2 = validDate2&&(cell_history.date_2)>date.getStartUTC()&&(cell_history.date_2)<date.getEndUTC();
                    var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                    var _item_counter = [cell_history.time,0,0];
                    
                    channel.statistics.count_full++;
                    if (type_package == 1)
                    {
                        if (correctTime&&!_items_counter[cell_history.time])
                        {
                            //Эту запись можно рассматривать как нормальный первый пакет
                            //фиксация
                            channel.statistics.count_all++;
                            channel.statistics.count_1++;
                            channel.statistics.countPackage_type_1++;
                            var t = parseFloat(cell_history.temperature);
                            if (!isNaN(t))
                            {
                                summ_t += t;
                                count_t++;
                            }
                            
                            _items_counter[cell_history.time]=true;
                            //-----------------------------------------//
                            if (cell_history.time<minDate&&validSensor)
                            {
                                minDate = cell_history.time;
                                minS = cell_history.sensor_rate_sum;
                            }
                            if (cell_history.time>maxDate&&validSensor)
                            {
                                maxDate = cell_history.time;
                                maxS = cell_history.sensor_rate_sum;
                            }
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_time=cell_history.time;
                                if (validSensor)channel.statistics.last_sensor_rate_sum=cell_history.sensor_rate_sum;
                                channel.statistics.last_release_date=cell_history.release_date;
                                channel.statistics.last_release_date_rus=moment.unix(channel.statistics.last_release_date).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_count_phase_1=cell_history.count_phase;
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_state_relay=cell_history.state_3;
                                channel.statistics.last_state_KK=cell_history.state_1;
                                channel.statistics.last_state_K=cell_history.state_2;
                                channel.statistics.last_relay=cell_history.relay_state;
                                channel.statistics.last_event=cell_history.event;
                            }
                            //ГРАФИК ТЕМПЕРАТУР
                            if (!_items_counter_all[cell_history.time])
                            {
                                channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                                _items_counter_all[cell_history.time]=true;
                            }
                            if (validSensor)
                            {
                                //ГРАФИК ПОКАЗАНИЙ
                                channel.statistics.chart.push( [cell_history.time*1000,cell_history.sensor_rate_sum,cell_history.event,cell_history.fcnt]);

                                channel.statistics.chart_consumption.push( [cell_history.time*1000,cell_history.sensor_rate_sum,cell_history.event,cell_history.fcnt] );

                                channel.statistics.arr_value_consum.push( [cell_history.time*1000,undefined,undefined,undefined,undefined,cell_history.sensor_rate_sum,undefined,undefined]);
                            }
                            if (cell_history.event==19)
                            {
                                _item_counter[1] = cell_history.event;
                                _item_counter[2] = 2;
                            }
                            else if (cell_history.event!=1)
                            {
                                _item_counter[1] = cell_history.event;
                                _item_counter[2] = 3;
                                channel.statistics.count_danger++;
                            }
                            //ГРАФИК СОБЫТИЙ
                            arr_value_4.push(_item_counter);
                        }
                        else if(validTime&&!_items_counter_all[cell_history.time]&&validSensor)
                        {
                            _items_counter_all[cell_history.time]=true;
                            channel.statistics.chart_consumption.push( [cell_history.time*1000,cell_history.sensor_rate_sum,cell_history.event,cell_history.fcnt] );
                        }
                    }
                    else if (type_package==4)
                    {
                        if (correctTime&&!_items_counter_2[cell_history.time])
                        {
                            channel.statistics.countPackage_type_4++;
                            _items_counter_2[cell_history.time]=true;
                            if (validSensor)
                            {
                                if (cell_history.time>channel.statistics.last_time)
                                {
                                    channel.statistics.last_time=cell_history.time;
                                    channel.statistics.last_sensor_rate_sum=cell_history.sensor_rate_sum;

                                }
                                var timeMS = cell_history.time*1000;
                                var sensor_rate_1 = cell_history.sensor_rate_1;
                                var sensor_rate_2 = cell_history.sensor_rate_2;
                                var sensor_rate_3 = cell_history.sensor_rate_3;
                                var sensor_rate_4 = cell_history.sensor_rate_4;
                                var sensor_rate_sum = cell_history.sensor_rate_sum;
                                var count_rate_active = cell_history.count_rate_active;
                                var rate_active = cell_history.rate_active;
                                var uuid = cell_history.UUID;
                                if (cell_history.time<minDate)
                                {
                                    minDate = cell_history.time;
                                    minS = cell_history.sensor_rate_sum;
                                }
                                if (cell_history.time>maxDate)
                                {
                                    maxDate = cell_history.time;
                                    maxS = cell_history.sensor_rate_sum;
                                }
                                if (!_items_counter_all[cell_history.time])
                                {
                                    channel.statistics.chart.push( [cell_history.time*1000,cell_history.sensor_rate_sum,0,cell_history.fcnt] );

                                    channel.statistics.chart_consumption.push( [cell_history.time*1000,cell_history.sensor_rate_sum,0,cell_history.fcnt] );

                                    _items_counter_all[cell_history.time]=true;
                                }
                                channel.statistics.arr_value_consum.push( [timeMS,sensor_rate_1,sensor_rate_2,sensor_rate_3,sensor_rate_4,sensor_rate_sum,count_rate_active,rate_active]);
                                if (uuid===undefined||uuid==='0000' )
                                {
                                
                                    channel.statistics.arr_value_consum_v4.push( [timeMS,sensor_rate_1,sensor_rate_2,sensor_rate_3,sensor_rate_4,sensor_rate_sum,count_rate_active,rate_active]);
                                }
                            }
                        }
                        else if(validTime&&!_items_counter_all[cell_history.time]&&validSensor)
                        {
                            _items_counter_all[cell_history.time]=true;
                            channel.statistics.chart_consumption.push( [cell_history.time*1000,cell_history.sensor_rate_sum,0,cell_history.fcnt] );
                        }
                    }
                    else if (type_package==5)
                    {
                        var history_p5 = cell_history;
                        var uuid = cell_history.UUID;
                        if ((correctDate1)&&(uuid===undefined||uuid==='0000' )&&!_items_counter_power[cell_history.date_1])
                        {
                            channel.statistics.countPackage_type_5++;
                            _items_counter_power[cell_history.date_1]= true;
                            channel.statistics.arr_power_profile.push(history_p5);
                        }
                    }
                    else if (type_package==2)
                    {
                        if (correctTime&&!_items_counter_p_2[cell_history.time])
                        {
                            _items_counter_p_2[cell_history.time] = true;
                            channel.statistics.countPackage_type_2++;
                        }
                    }
                }
                else if (ue_spbzip)
                {
                    //ue
                    var type_package = cell_history.type;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var validDate1 = cell_history.date_1!==undefined&&cell_history.date_1>0;
                    var validDate2 = cell_history.date_2!==undefined&&cell_history.date_2>0;
                    var correctTime = validTime&&(cell_history.time)>=date.getStartUTC()&&(cell_history.time)<=date.getEndUTC();
                    var correctDate1 = validDate1&&(cell_history.date_1)>date.getStartUTC()&&(cell_history.date_1)<date.getEndUTC();
                    var correctDate2 = validDate2&&(cell_history.date_2)>date.getStartUTC()&&(cell_history.date_2)<date.getEndUTC();
                    var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                    var _item_counter = [cell_history.time,0,0];
                    
                    if( channel.statistics['countPackage_type_'+type_package] === undefined ) channel.statistics['countPackage_type_'+type_package] = 0;
                    channel.statistics['countPackage_type_'+type_package]++;

                    channel.statistics.count_full++;
                    if (type_package == 1)
                    {
                        if (correctTime&&!_items_counter[cell_history.time])
                        {
                            //Эту запись можно рассматривать как нормальный первый пакет
                            //фиксация
                            channel.statistics.count_all++;
                            channel.statistics.count_1++;
                            // channel.statistics.countPackage_type_1++;
                            var t = parseFloat(cell_history.temperature);
                            if (!isNaN(t))
                            {
                                summ_t += t;
                                count_t++;
                            }
                            
                            _items_counter[cell_history.time]=true;
                            //-----------------------------------------//
                            if (cell_history.time<minDate&&validSensor)
                            {
                                minDate = cell_history.time;
                                minS = cell_history.sensor_rate_sum;
                            }
                            if (cell_history.time>maxDate&&validSensor)
                            {
                                maxDate = cell_history.time;
                                maxS = cell_history.sensor_rate_sum;
                            }
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_time=cell_history.time;
                                if (validSensor)channel.statistics.last_sensor_rate_sum=cell_history.sensor_rate_sum;
                                channel.statistics.last_release_date=cell_history.release_date;
                                channel.statistics.last_release_date_rus=moment.unix(channel.statistics.last_release_date).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_count_phase_1=cell_history.count_phase;
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_state_relay=cell_history.state_3;
                                channel.statistics.last_state_KK=cell_history.state_1;
                                channel.statistics.last_state_K=cell_history.state_2;
                                channel.statistics.last_relay=cell_history.relay_state;
                                channel.statistics.last_event=cell_history.event;
                            }
                            //ГРАФИК ТЕМПЕРАТУР
                            if (!_items_counter_all[cell_history.time])
                            {
                                channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                                _items_counter_all[cell_history.time]=true;
                            }
                            if (validSensor)
                            {
                                //ГРАФИК ПОКАЗАНИЙ
                                channel.statistics.chart.push( [cell_history.time*1000,cell_history.sensor_rate_sum,cell_history.event,cell_history.fcnt]);

                                channel.statistics.chart_consumption.push( [cell_history.time*1000,cell_history.sensor_rate_sum,cell_history.event,cell_history.fcnt] );

                                channel.statistics.arr_value_consum.push( [cell_history.time*1000,undefined,undefined,undefined,undefined,cell_history.sensor_rate_sum,undefined,undefined]);
                            }
                            if (cell_history.event==19)
                            {
                                _item_counter[1] = cell_history.event;
                                _item_counter[2] = 2;
                            }
                            else if (cell_history.event!=1)
                            {
                                _item_counter[1] = cell_history.event;
                                _item_counter[2] = 3;
                                channel.statistics.count_danger++;
                            }
                            //ГРАФИК СОБЫТИЙ
                            arr_value_4.push(_item_counter);
                        }
                        else if(validTime&&!_items_counter_all[cell_history.time]&&validSensor)
                        {
                            _items_counter_all[cell_history.time]=true;
                            channel.statistics.chart_consumption.push( [cell_history.time*1000,cell_history.sensor_rate_sum,cell_history.event,cell_history.fcnt] );
                        }
                    }
                    else if (type_package==4)
                    {
                        if (correctTime&&!_items_counter_2[cell_history.time])
                        {
                            // channel.statistics.countPackage_type_4++;
                            _items_counter_2[cell_history.time]=true;
                            if (validSensor)
                            {
                                if (cell_history.time>channel.statistics.last_time)
                                {
                                    channel.statistics.last_time=cell_history.time;
                                    channel.statistics.last_sensor_rate_sum=cell_history.sensor_rate_sum;

                                }
                                var timeMS = cell_history.time*1000;
                                var sensor_rate_1 = cell_history.sensor_rate_1;
                                var sensor_rate_2 = cell_history.sensor_rate_2;
                                var sensor_rate_3 = cell_history.sensor_rate_3;
                                var sensor_rate_4 = cell_history.sensor_rate_4;
                                var sensor_rate_sum = cell_history.sensor_rate_sum;
                                var count_rate_active = cell_history.count_rate_active;
                                var rate_active = cell_history.rate_active;
                                var uuid = cell_history.UUID;
                                if (cell_history.time<minDate)
                                {
                                    minDate = cell_history.time;
                                    minS = cell_history.sensor_rate_sum;
                                }
                                if (cell_history.time>maxDate)
                                {
                                    maxDate = cell_history.time;
                                    maxS = cell_history.sensor_rate_sum;
                                }
                                if (!_items_counter_all[cell_history.time])
                                {
                                    channel.statistics.chart.push( [cell_history.time*1000,cell_history.sensor_rate_sum,0,cell_history.fcnt]);
                                    
                                    channel.statistics.chart_consumption.push( [cell_history.time*1000,cell_history.sensor_rate_sum,0,cell_history.fcnt] );

                                    _items_counter_all[cell_history.time]=true;
                                }
                                channel.statistics.arr_value_consum.push( [timeMS,sensor_rate_1,sensor_rate_2,sensor_rate_3,sensor_rate_4,sensor_rate_sum,count_rate_active,rate_active]);
                                // if (uuid===undefined||uuid==='0000' )
                                // {
                                
                                    channel.statistics.arr_value_consum_v4.push( [timeMS,sensor_rate_1,sensor_rate_2,sensor_rate_3,sensor_rate_4,sensor_rate_sum,count_rate_active,rate_active]);
                                // }
                            }
                        }
                        else if(validTime&&!_items_counter_all[cell_history.time]&&validSensor)
                        {
                            _items_counter_all[cell_history.time]=true;
                            channel.statistics.chart_consumption.push( [cell_history.time*1000,cell_history.sensor_rate_sum,0,cell_history.fcnt] );
                        }
                    }
                    else if (type_package==5)
                    {
                        var history_p5 = cell_history;
                        var uuid = cell_history.UUID;
                        if ((correctDate1)&&(uuid===undefined||uuid==='0000' )&&!_items_counter_power[cell_history.date_1])
                        {
                            // channel.statistics.countPackage_type_5++;
                            _items_counter_power[cell_history.date_1]= true;
                            channel.statistics.arr_power_profile.push(history_p5);
                        }
                    }
                    else if (type_package==2)
                    {
                        if (correctTime&&!_items_counter_p_2[cell_history.time])
                        {
                            _items_counter_p_2[cell_history.time] = true;
                            // channel.statistics.countPackage_type_2++;
                        }
                    }
                }
                else if (mbus)
                {
                    //mbus
                    var type_package = cell_history.type;

                    var validTime = cell_history.time !== undefined && cell_history.time > 0;
                    var validTs = cell_history.ts !== undefined && cell_history.ts > 0;
                    var correctTime = validTime && cell_history.time >= date.getStart() && cell_history.time <= date.getEnd();
                    var correctTs = validTs && cell_history.ts >= ( date.getStart() * 1000 ) && cell_history.ts <= ( date.getEnd() * 1000 );
                    var validSensor = cell_history.sensor_rate_sum !== undefined && typeof cell_history.sensor_rate_sum === 'number';
                    var danger = cell_history.sensor_11;
                    var danger2 = cell_history.sensor_12;
                    var _item_counter = [cell_history.ts,0,0];
                    var timeMs = cell_history.time * 1000; 
                    channel.statistics.count_full++;
                    var typeHeat = channel.type_channel == 20;

                    

                    if ( type_package == 1 )
                    {
                        _item_counter[0] = timeMs;
                        var last = cell_history.time > channel.statistics.last_time;
                        
                        if ( typeof channel.statistics.countPackage_type_1 !== 'number' ) channel.statistics.countPackage_type_1 = 0;
                        channel.statistics.countPackage_type_1++;
                        var currentAddress = parseInt(`0x${cell_history.address}`); 
                        var validAddress = currentAddress == channel.ia;
                        if( typeHeat && validAddress )
                        {
                            if ( last )
                            {
                                channel.statistics.last_ts = cell_history.ts;
                                channel.statistics.last_time = cell_history.time;
                                channel.statistics.last_temperature = cell_history.temperature;
                                channel.statistics.last_temperature_2 = cell_history.temperature_2;
                                channel.statistics.last_charge = cell_history.charge;
                                channel.statistics.last_sensor_rate_sum = cell_history.sensor_rate_sum;
                                channel.statistics.last_total_heat_carrier_volume = cell_history.total_heat_carrier_volume;
                                channel.statistics.last_working_time_h = cell_history.working_time_h;
                                channel.statistics.last_current_coolant_flow = cell_history.current_coolant_flow;
                                channel.statistics.last_ts_rus = moment( cell_history.ts ).format( 'DD.MM.YY HH:mm' );
                                channel.statistics.last_time_rus = moment( timeMs ).format( 'DD.MM.YY HH:mm' );
                                channel.statistics.last_fcnt = cell_history.fcnt;
                                channel.statistics.last_cell_history = cell_history
                            }

                            if ( correctTime && !_items_counter[timeMs] )
                            {
                                _items_counter[timeMs] = true;
                                if ( cell_history.time < minDate )
                                {
                                    minDate = cell_history.time;
                                    minS = cell_history.sensor_rate_sum;
                                }
                                if ( cell_history.time > maxDate )
                                {
                                    maxDate = cell_history.time;
                                    maxS = cell_history.sensor_rate_sum;
                                }
                                if (validSensor)
                                {
                                    channel.statistics.chart.push( [timeMs,cell_history.sensor_rate_sum,0] );
                                    channel.statistics.chart_consumption.push( [timeMs,cell_history.sensor_rate_sum,0,cell_history.fcnt] );
                                }
                                channel.statistics.chart_temperature.push( [timeMs, cell_history.temperature, cell_history.temperature_2] );
                            }
                            else if(validTime&&!_items_counter[timeMs]&&validSensor)
                            {
                                _items_counter[timeMs]=true;
                                channel.statistics.chart_consumption.push( [timeMs,cell_history.sensor_rate_sum,0,cell_history.fcnt] );
                            }
                        }
                        
                    }
                    else if ( type_package == 3 && mbus1 )
                    {
                        if ( typeof channel.statistics.countPackage_type_3 !== 'number' ) channel.statistics.countPackage_type_3 = 0;
                        channel.statistics.countPackage_type_3++;
                    }
                    else if ( type_package == 4 && mbus1 )
                    {
                        if ( typeof channel.statistics.countPackage_type_4 !== 'number' ) channel.statistics.countPackage_type_4 = 0;
                        channel.statistics.countPackage_type_4++;
                    }
                    else if ( type_package == 5 && mbus1 )
                    {
                        channel.statistics.count_full++;
                        if ( typeof channel.statistics.countPackage_type_5 !== 'number' ) channel.statistics.countPackage_type_5 = 0;
                        channel.statistics.countPackage_type_5++;

                        if ( correctTs && !_items_counter[cell_history.ts] )
                        {
                            var last = cell_history.ts > channel.statistics.last_ts;
                            _items_counter[cell_history.ts] = true;
                            if ( channel.num_channel == 11 && cell_history.num_channel == 1 )
                            {
                                channel.statistics.count_danger++;
                                channel.statistics.chart.push( [cell_history.ts, danger, 1] );
                                channel.statistics.chart_consumption.push( [cell_history.ts, danger, 1,cell_history.fcnt] );
                                arr_value.push( [cell_history.ts,1]);
                            } 
                            if ( channel.num_channel == 12 && cell_history.num_channel == 2 ) 
                            {
                                channel.statistics.count_danger++;
                                channel.statistics.chart.push( [cell_history.ts, danger2, 1] );

                                channel.statistics.chart_consumption.push( [cell_history.ts, danger2, 1,cell_history.fcnt] );

                                arr_value.push( [cell_history.ts,1] );
                            }
                            if ( last )
                            {
                                channel.statistics.last_ts = cell_history.ts;
                                channel.statistics.last_charge = cell_history.charge;
                                channel.statistics.last_ts_rus = moment( cell_history.ts ).format( 'DD.MM.YY HH:mm' );
                                channel.statistics.last_fcnt = cell_history.fcnt;
                                channel.statistics.last_cell_history = cell_history
                            }
                        }
                        else if( validTs && !_items_counter[cell_history.ts] )
                        {
                            _items_counter[cell_history.ts] = true;
                            if ( channel.num_channel == 11 && cell_history.num_channel == 1 )
                            {
                                channel.statistics.chart_consumption.push( [cell_history.ts, danger, 1,cell_history.fcnt] );
                            } 
                            if ( channel.num_channel == 12 && cell_history.num_channel == 2 ) 
                            {
                                channel.statistics.chart_consumption.push( [cell_history.ts, danger2, 1,cell_history.fcnt] );
                            }
                        }
                    }
                    else if ( type_package == 6 && mbus1 )
                    {
                        if ( typeof channel.statistics.countPackage_type_6 !== 'number' ) channel.statistics.countPackage_type_6 = 0;
                        channel.statistics.countPackage_type_6++;
                        var valid_sensor_out_1_lastTime = last_sensor_out_1.ts === null || cell_history.ts > last_sensor_out_1.ts;
                        var valid_sensor_out_2_lastTime = last_sensor_out_2.ts === null || cell_history.ts > last_sensor_out_2.ts;
                        if (valid_sensor_out_1_lastTime && cell_history.num_out_channel == 1 )
                        {
                            last_sensor_out_1.ts = cell_history.ts;
                            last_sensor_out_1.time = cell_history.time;
                            last_sensor_out_1.value = cell_history.sensor_out_1;
                        }
                        if (valid_sensor_out_2_lastTime && cell_history.num_out_channel == 2)
                        {
                            last_sensor_out_2.ts = cell_history.ts;
                            last_sensor_out_2.time = cell_history.time;
                            last_sensor_out_2.value = cell_history.sensor_out_2;
                        }
                    }

                }
                else if (thermo)
                {
                    //thermo
                    var type_package = cell_history.type;

                    var validTime = cell_history.time !== undefined && cell_history.time > 0;
                    var validTs = cell_history.ts !== undefined && cell_history.ts > 0;
                    var correctTime = validTime && cell_history.time >= date.getStart() && cell_history.time <= date.getEnd();
                    var correctTs = validTs && cell_history.ts >= ( date.getStart() * 1000 ) && cell_history.ts <= ( date.getEnd() * 1000 );
                    // var validSensor = cell_history.sensor_rate_sum !== undefined && typeof cell_history.sensor_rate_sum === 'number';
                    var _item_counter = [cell_history.ts,0,0];
                    var timeMs = cell_history.time * 1000; 
                    channel.statistics.count_full++;
                    var typeHeat = channel.type_channel == 30;
                    if ( type_package == 1 )
                    {
                        _item_counter[0] = timeMs;
                        var last = cell_history.time > channel.statistics.last_time;
                        
                        if ( typeof channel.statistics.countPackage_type_1 !== 'number' ) channel.statistics.countPackage_type_1 = 0;
                        channel.statistics.countPackage_type_1++;
                        var currentAddress = cell_history.address.toLowerCase(); 
                        var validAddress = currentAddress == channel.mac.toLowerCase();
                        if( typeHeat && validAddress )
                        {
                            if ( last )
                            {
                                 channel.statistics.last_ts = cell_history.ts;
                                 channel.statistics.last_time = cell_history.time;
                                 channel.statistics.last_mv = cell_history.mv;
                                 channel.statistics.last_num_package = cell_history.num_package;
                                 channel.statistics.last_rssi_sensor = cell_history.rssi_sensor;
                                 for(var i = 0; i<=12; i++)
                                {
                                    channel.statistics[`last_temperature_num_${i}`] = cell_history[`temperature_num_${i}`];
                                }
                                // channel.statistics.last_temperature = cell_history.temperature;
                                // channel.statistics.last_temperature_2 = cell_history.temperature_2;
                                // channel.statistics.last_charge = cell_history.charge;
                                // channel.statistics.last_sensor_rate_sum = cell_history.sensor_rate_sum;
                                // channel.statistics.last_total_heat_carrier_volume = cell_history.total_heat_carrier_volume;
                                // channel.statistics.last_working_time_h = cell_history.working_time_h;
                                // channel.statistics.last_current_coolant_flow = cell_history.current_coolant_flow;
                                channel.statistics.last_ts_rus = moment( cell_history.ts ).format( 'DD.MM.YY HH:mm' );
                                channel.statistics.last_time_rus = moment( timeMs ).format( 'DD.MM.YY HH:mm' );
                                channel.statistics.last_fcnt = cell_history.fcnt;
                                channel.statistics.last_cell_history = cell_history
                            }

                            if ( correctTime && !_items_counter[timeMs] )
                            {
                                _items_counter[timeMs] = true;
                                if ( cell_history.time < minDate )
                                {
                                    minDate = cell_history.time;
                                    minS = cell_history.temperature_num_0;
                                }
                                if ( cell_history.time > maxDate )
                                {
                                    maxDate = cell_history.time;
                                    maxS = cell_history.temperature_num_0;
                                }
                                // if (validSensor)
                                // {
                                //     channel.statistics.chart.push( [timeMs,cell_history.sensor_rate_sum,0] );
                                //     channel.statistics.chart_consumption.push( [timeMs,cell_history.sensor_rate_sum,0,cell_history.fcnt] );
                                // }
                                var validT = cell_history.temperature_num_0 <= 250;
                                if(validT)
                                {
                                    channel.statistics.chart_temperature.push( [timeMs, (cell_history.temperature_num_0/10)+20] );
                                }
                                
                            }
                            // else if(validTime&&!_items_counter[timeMs]&&validSensor)
                            // {
                            //     _items_counter[timeMs]=true;
                            //     // channel.statistics.chart_consumption.push( [timeMs,cell_history.sensor_rate_sum,0,cell_history.fcnt] );
                            // }
                        }
                        
                    }
                    // else if ( type_package == 3 && mbus1 )
                    // {
                    //     if ( typeof channel.statistics.countPackage_type_3 !== 'number' ) channel.statistics.countPackage_type_3 = 0;
                    //     channel.statistics.countPackage_type_3++;
                    // }
                    // else if ( type_package == 4 && mbus1 )
                    // {
                    //     if ( typeof channel.statistics.countPackage_type_4 !== 'number' ) channel.statistics.countPackage_type_4 = 0;
                    //     channel.statistics.countPackage_type_4++;
                    // }
                    // else if ( type_package == 5 && mbus1 )
                    // {
                    //     channel.statistics.count_full++;
                    //     if ( typeof channel.statistics.countPackage_type_5 !== 'number' ) channel.statistics.countPackage_type_5 = 0;
                    //     channel.statistics.countPackage_type_5++;

                    //     if ( correctTs && !_items_counter[cell_history.ts] )
                    //     {
                    //         var last = cell_history.ts > channel.statistics.last_ts;
                    //         _items_counter[cell_history.ts] = true;
                    //         if ( channel.num_channel == 11 && cell_history.num_channel == 1 )
                    //         {
                    //             channel.statistics.count_danger++;
                    //             channel.statistics.chart.push( [cell_history.ts, danger, 1] );
                    //             channel.statistics.chart_consumption.push( [cell_history.ts, danger, 1,cell_history.fcnt] );
                    //             arr_value.push( [cell_history.ts,1]);
                    //         } 
                    //         if ( channel.num_channel == 12 && cell_history.num_channel == 2 ) 
                    //         {
                    //             channel.statistics.count_danger++;
                    //             channel.statistics.chart.push( [cell_history.ts, danger2, 1] );

                    //             channel.statistics.chart_consumption.push( [cell_history.ts, danger2, 1,cell_history.fcnt] );

                    //             arr_value.push( [cell_history.ts,1] );
                    //         }
                    //         if ( last )
                    //         {
                    //             channel.statistics.last_ts = cell_history.ts;
                    //             channel.statistics.last_charge = cell_history.charge;
                    //             channel.statistics.last_ts_rus = moment( cell_history.ts ).format( 'DD.MM.YY HH:mm' );
                    //             channel.statistics.last_fcnt = cell_history.fcnt;
                    //             channel.statistics.last_cell_history = cell_history
                    //         }
                    //     }
                    //     else if( validTs && !_items_counter[cell_history.ts] )
                    //     {
                    //         _items_counter[cell_history.ts] = true;
                    //         if ( channel.num_channel == 11 && cell_history.num_channel == 1 )
                    //         {
                    //             channel.statistics.chart_consumption.push( [cell_history.ts, danger, 1,cell_history.fcnt] );
                    //         } 
                    //         if ( channel.num_channel == 12 && cell_history.num_channel == 2 ) 
                    //         {
                    //             channel.statistics.chart_consumption.push( [cell_history.ts, danger2, 1,cell_history.fcnt] );
                    //         }
                    //     }
                    // }
                    // else if ( type_package == 6 && mbus1 )
                    // {
                    //     if ( typeof channel.statistics.countPackage_type_6 !== 'number' ) channel.statistics.countPackage_type_6 = 0;
                    //     channel.statistics.countPackage_type_6++;
                    //     var valid_sensor_out_1_lastTime = last_sensor_out_1.time === null || cell_history.time > last_sensor_out_1.time;
                    //     var valid_sensor_out_2_lastTime = last_sensor_out_2.time === null || cell_history.time > last_sensor_out_2.time;
                    //     if (valid_sensor_out_1_lastTime && cell_history.num_out_channel == 1 )
                    //     {
                    //         last_sensor_out_1.ts = cell_history.ts;
                    //         last_sensor_out_1.time = cell_history.time;
                    //         last_sensor_out_1.value = cell_history.sensor_out_1;
                    //     }
                    //     if (valid_sensor_out_2_lastTime && cell_history.num_out_channel == 2)
                    //     {
                    //         last_sensor_out_2.ts = cell_history.ts;
                    //         last_sensor_out_2.time = cell_history.time;
                    //         last_sensor_out_2.value = cell_history.sensor_out_2;
                    //     }
                    // }

                }
                else if (si13)
                {
                    //si13
                    var type_package = cell_history.type;
                    var validTime = cell_history.ts!==undefined&&cell_history.ts>0;
                    var correctTime = validTime&&cell_history.ts>=(date.getStart()*1000)&&cell_history.ts<=(date.getEnd()*1000);
                    var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                    var validSensor1 = cell_history.sensor_7!==undefined&&typeof cell_history.sensor_7 === 'number';
                    var validSensor2 = cell_history.sensor_8!==undefined&&typeof cell_history.sensor_8 === 'number';
                    var _item_counter = [cell_history.ts,0,0];
                    var port = cell_history.port;
                    channel.statistics.count_full++;
                    if (validTime&&!_items_counter[cell_history.ts]&&port==2)
                    {
                        channel.statistics.count_all++;
                        var ia;
                        var validMer = false;
                        if (cell_history.address!==undefined)
                        {
                            ia = parseInt(cell_history.address,16);
                            if (!isNaN(ia)&&ia==channel.ia)
                            {
                                validMer = true;
                            }
                        }
                        if (type_package == 4 && validMer)
                        {
                            channel.statistics.countPackage_type_4++;
                            if (cell_history.ts>channel.statistics.last_ts)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_sensor_rate_sum=cell_history.sensor_rate_sum;
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                            }
                            if (correctTime&&!_items_counter[cell_history.ts])
                            {
                                _items_counter[cell_history.ts]=true;
                                if (cell_history.ts<minDate)
                                {
                                    minDate = cell_history.ts;
                                    minS = cell_history.sensor_rate_sum;
                                }
                                if (cell_history.ts>maxDate)
                                {
                                    maxDate = cell_history.ts;
                                    maxS = cell_history.sensor_rate_sum;
                                }
                                if (validSensor)
                                {
                                    //ГРАФИК ПОКАЗАНИЙ
                                    channel.statistics.chart.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_rate_sum,0] );
                                    channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_rate_sum,0,cell_history.fcnt] );
                                    channel.statistics.arr_value_consum_v4.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_rate_1,cell_history.sensor_rate_2,cell_history.sensor_rate_3,cell_history.sensor_rate_4,cell_history.sensor_rate_sum,undefined,undefined]);
                                }
                            }
                            else if( validTime && !_items_counter[cell_history.ts] && validSensor)
                            {
                                _items_counter[cell_history.ts]=true;
                                channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_rate_sum,0,cell_history.fcnt] );
                            }
                        }
                        else if (type_package == 1)
                        {
                            channel.statistics.countPackage_type_1++;
                            if (cell_history.ts>channel.statistics.last_ts)
                            {
                                channel.statistics.last_temperature=cell_history.temperature
                                channel.statistics.last_ts=cell_history.ts;
                                if (channel.num_channel==7)channel.statistics.last_sensor=cell_history.sensor_7;
                                if (channel.num_channel==8)channel.statistics.last_sensor=cell_history.sensor_8;
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                            }
                            if (correctTime&&!_items_counter[cell_history.ts])
                            {
                                _items_counter[cell_history.ts]=true;
                                if (cell_history.ts<minDate)
                                {
                                    minDate = cell_history.ts;
                                    if (channel.num_channel==7) minS = cell_history.sensor_7;
                                    if (channel.num_channel==8) minS = cell_history.sensor_8;
                                }
                                if (cell_history.ts>maxDate)
                                {
                                    maxDate = cell_history.ts;
                                    if (channel.num_channel==7) maxS = cell_history.sensor_7;
                                    if (channel.num_channel==8) maxS = cell_history.sensor_8;
                                }
                                    //ГРАФИК ПОКАЗАНИЙ
                                if (channel.num_channel==7&&validSensor1) channel.statistics.chart.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_7,0]);
                                if (channel.num_channel==8&&validSensor2) channel.statistics.chart.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_8,0]);

                                if (channel.num_channel==7&&validSensor1) channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_7,0,cell_history.fcnt]);
                                if (channel.num_channel==8&&validSensor2) channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_8,0,cell_history.fcnt]);
                                
                                if (cell_history.temperature!==undefined) channel.statistics.chart_temperature.push( [cell_history.ts,cell_history.temperature]);
                            }
                            else if( validTime && !_items_counter[cell_history.ts] )
                            {
                                _items_counter[cell_history.ts]=true;
                                if (channel.num_channel==7&&validSensor1) channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_7,0,cell_history.fcnt]);
                                if (channel.num_channel==8&&validSensor2) channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_8,0,cell_history.fcnt]);
                            }
                        }
                        else if (type_package == 2)
                        {
                            channel.statistics.countPackage_type_2++;
                            if (cell_history.ts>channel.statistics.last_ts)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_ts=cell_history.ts;
                                if (channel.num_channel==7)channel.statistics.last_sensor=cell_history.sensor_7;
                                if (channel.num_channel==8)channel.statistics.last_sensor=cell_history.sensor_8;
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                            }
                            var validNumChannel = (cell_history.num_channel+6)==channel.num_channel;
                            if (correctTime&&!_items_counter[cell_history.ts])
                            {
                                _items_counter[cell_history.ts]=true;
                                if (cell_history.ts<minDate)
                                {
                                    minDate = cell_history.ts;
                                    if (channel.num_channel==7) minS = cell_history.sensor_7;
                                    if (channel.num_channel==8) minS = cell_history.sensor_8;
                                }
                                if (cell_history.ts>maxDate)
                                {
                                    maxDate = cell_history.ts;
                                    if (channel.num_channel==7) maxS = cell_history.sensor_7;
                                    if (channel.num_channel==8) maxS = cell_history.sensor_8;
                                }
                                if (channel.num_channel==7&&validSensor1&&validNumChannel )
                                {
                                    channel.statistics.chart.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_7,1]);
                                    channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_7,1,cell_history.fcnt]);
                                    
                                    if (!arr_ts_list[cell_history.ts])
                                    {
                                        arr_ts_list[cell_history.ts] = true;
                                        channel.statistics.count_danger++;
                                    }
                                }
                                if (channel.num_channel==8&&validSensor2&&validNumChannel) 
                                {
                                    channel.statistics.chart.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_8,1]);
                                    channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_8,1,cell_history.fcnt]);
                                    
                                    if (!arr_ts_list[cell_history.ts])
                                    {
                                        arr_ts_list[cell_history.ts] = true;
                                        channel.statistics.count_danger++;
                                    }
                                }
                                arr_value.push( [cell_history.ts,1]);
                                
                            }
                            else if( validTime && !_items_counter[cell_history.ts] )
                            {
                                _items_counter[cell_history.ts]=true;
                                if (channel.num_channel==7&&validSensor1&&validNumChannel )
                                {
                                    channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_7,1,cell_history.fcnt]);
                                }
                                if (channel.num_channel==8&&validSensor2&&validNumChannel) 
                                {
                                    channel.statistics.chart_consumption.push( [cell_history.ts+(get_time_zone()*1000),cell_history.sensor_8,1,cell_history.fcnt]);
                                }
                            }
                        }
                    }
                }
                else if (sh02rev3)
                {
                    var type_package = cell_history.type;


                    var validType = type_package == 0x0A ||
                        type_package == 0x0A ||
                        type_package == 0x0B ||
                        type_package == 0x0D ||
                        type_package == 4 ||
                        type_package == 5 ||
                        type_package == 6 ||
                        type_package == 0xAA ||
                        type_package == 0x0C;
                    var type1Wire  = type_package == 0x0B;
                    var typeModBus = type_package == 4 || type_package == 6;
                    var tz = get_time_zone()*1000;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var validSensor1 = cell_history.sensor_1!==undefined&&typeof cell_history.sensor_1 === 'number';
                    var validSensor2 = cell_history.sensor_2!==undefined&&typeof cell_history.sensor_2 === 'number';
                    var validSensor3 = cell_history.sensor_3!==undefined&&typeof cell_history.sensor_3 === 'number';
                    var validSensor4 = cell_history.sensor_4!==undefined&&typeof cell_history.sensor_4 === 'number';
                    var timeMS = validTime?cell_history.time*1000:undefined;
                    var _item_counter = [timeMS,0,0];
                    var port = 2;
                    channel.statistics.count_full++;
                    var lastHistory = cell_history.time>channel.statistics.last_time;
                    var lastCharge = cell_history.time>(channel.statistics.last_time_charge || 0);
                    var last1Wire = cell_history.time>(channel.statistics.last_time_1wire || 0);
                    console.log(lastHistory, lastCharge, last1Wire, type_package,   channel.statistics.last_time_charge, channel.statistics.last_time_1wire, cell_history.time)
                    var dangerChannel1 = channel.num_channel == 1 && cell_history.reason == 2;
                    var dangerChannel2 = channel.num_channel == 2 && cell_history.reason == 3;
                    if (validTime&&!_items_counter[timeMS]&&port==2)
                    {
                        channel.statistics.count_all++;

                        if( validType )
                        {
                            if (lastHistory)
                            {
                                channel.statistics.last_temperature = cell_history.temperature;
                                channel.statistics.last_ts = cell_history.ts;
                                channel.statistics.last_time = cell_history.time;
                                channel.statistics.last_ts_rus = moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_time_rus = moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_reason = cell_history.reason;
                                if(cell_history.charge) channel.statistics.last_charge = cell_history.charge;
                                channel.statistics.last_sensor = cell_history.sensor;
                                channel.statistics.last_sensor_1 = cell_history.sensor_1;
                                channel.statistics.last_sensor_2 = cell_history.sensor_2;
                                channel.statistics.last_sensor_3 = cell_history.sensor_3;
                                channel.statistics.last_sensor_4 = cell_history.sensor_4;
                                for(var t = 0; t<=10; t++)
                                {
                                    if(!cell_history[`temperature_1wire_${t}`]) continue;
                                    channel.statistics[`last_temperature_1wire_${t}`]  = cell_history[`temperature_1wire_${t}`];
                                }
                            }
                            if(lastCharge && cell_history.charge){
                                channel.statistics.last_time_charge = cell_history.time;
                                channel.statistics.last_charge = cell_history.charge;
                            }
                            if(correctTime)
                            {
                                if( dangerChannel1 || dangerChannel2 ) 
                                {
                                    channel.statistics.count_danger++;
                                    arr_value.push( [timeMS,1]);
                                }
                                if (timeMS<minDate)
                                {
                                    minDate = timeMS;
                                    if (channel.num_channel==1) minS = cell_history.sensor_1;
                                    if (channel.num_channel==2) minS = cell_history.sensor_2;
                                }
                                if (timeMS>maxDate)
                                {
                                    maxDate = timeMS;
                                    if (channel.num_channel==1) maxS = cell_history.sensor_1;
                                    if (channel.num_channel==2) maxS = cell_history.sensor_2;
                                }
                                
                                channel.statistics.chart_sensor_new.push( [timeMS+(tz),cell_history.sensor]);
                                
                                channel.statistics.chart.push( [timeMS+tz,cell_history.sensor,0]);
                                channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor,0,cell_history.fcnt]);
                                if (cell_history.temperature!==undefined) channel.statistics.chart_temperature.push( [timeMS,cell_history.temperature]);
                            }
                        }

                        if ( type1Wire )
                        {
                            if (last1Wire)
                            {
                                channel.statistics.last_time_1wire = cell_history.time;
                                for(var t = 1; t<=10; t++)
                                {
                                    channel.statistics[`last_temperature_1wire_${t}`] = cell_history[`temperature_1wire_${t}`];
                                }
                            }
                            if(correctTime)
                            {
                                channel.statistics.chart_t.push( [timeMS,cell_history.temperature,cell_history.temperature_1wire_1,cell_history.temperature_1wire_2,cell_history.temperature_1wire_3,cell_history.temperature_1wire_4,cell_history.temperature_1wire_5,cell_history.temperature_1wire_6,cell_history.temperature_1wire_7,cell_history.temperature_1wire_8,cell_history.temperature_1wire_9,cell_history.temperature_1wire_10]);
                            }
                            channel.statistics.countPackage_type_1++;
                        }
                        else if ( typeModBus )
                        {
                            if (lastHistory)
                            {
                                channel.statistics.last_data = cell_history.data_b;
                            }
                            channel.statistics.countPackage_type_9++;
                        }
                        
                    }
                    if(correctTime)
                    {
                        arr_date.push(moment(timeMS).format('LLL' ).replace(',',' ' ));
                    }
                }
                else if (sh02rev2)
                {
                    var type_package = cell_history.type;
                    var validType = type_package == 10;
                    var type1Wire  = cell_history.type2 == 12;
                    var typeModBus = cell_history.type2 == 13;
                    var tz = get_time_zone()*1000;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var validSensor1 = cell_history.sensor_1!==undefined&&typeof cell_history.sensor_1 === 'number';
                    var validSensor2 = cell_history.sensor_2!==undefined&&typeof cell_history.sensor_2 === 'number';
                    var validSensor3 = cell_history.sensor_3!==undefined&&typeof cell_history.sensor_3 === 'number';
                    var validSensor4 = cell_history.sensor_4!==undefined&&typeof cell_history.sensor_4 === 'number';
                    var timeMS = validTime?cell_history.time*1000:undefined;
                    var _item_counter = [timeMS,0,0];
                    var port = 2;
                    channel.statistics.count_full++;
                    var lastHistory = cell_history.time>channel.statistics.last_time;
                    var dangerChannel1 = channel.num_channel == 1 && cell_history.reason == 2;
                    var dangerChannel2 = channel.num_channel == 2 && cell_history.reason == 3;
                    if (validTime&&!_items_counter[timeMS]&&port==2)
                    {
                        channel.statistics.count_all++;

                        if( validType )
                        {
                            if (lastHistory)
                            {
                                channel.statistics.last_temperature = cell_history.temperature;
                                channel.statistics.last_ts = cell_history.ts;
                                channel.statistics.last_time = cell_history.time;
                                channel.statistics.last_ts_rus = moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_time_rus = moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_reason = cell_history.reason;
                                channel.statistics.last_charge = cell_history.charge;
                                channel.statistics.last_sensor= cell_history.sensor;
                                channel.statistics.last_sensor_1 = cell_history.sensor_1;
                                channel.statistics.last_sensor_2 = cell_history.sensor_2;
                                channel.statistics.last_sensor_3 = cell_history.sensor_3;
                                channel.statistics.last_sensor_4 = cell_history.sensor_4;
                                for(var t = 0; t<=10; t++)
                                {
                                    channel.statistics[`last_temperature_1wire_${t}`]  = cell_history[`temperature_1wire_${t}`];
                                }
                            }
                            if(correctTime)
                            {
                                if( dangerChannel1 || dangerChannel2 ) 
                                {
                                    channel.statistics.count_danger++;
                                    arr_value.push( [timeMS,1]);
                                }
                                if (timeMS<minDate)
                                {
                                    minDate = timeMS;
                                    if (channel.num_channel==1) minS = cell_history.sensor_1;
                                    if (channel.num_channel==2) minS = cell_history.sensor_2;
                                }
                                if (timeMS>maxDate)
                                {
                                    maxDate = timeMS;
                                    if (channel.num_channel==1) maxS = cell_history.sensor_1;
                                    if (channel.num_channel==2) maxS = cell_history.sensor_2;
                                }
                                
                                channel.statistics.chart_sensor_new.push( [timeMS+(tz),cell_history.sensor]);
                                
                                channel.statistics.chart.push( [timeMS+tz,cell_history.sensor,0]);
                                channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor,0,cell_history.fcnt]);
                                if (cell_history.temperature!==undefined) channel.statistics.chart_temperature.push( [timeMS,cell_history.temperature]);
                            }
                        }

                        if ( type1Wire )
                        {
                            if (lastHistory)
                            {
                                for(var t = 1; t<=10; t++)
                                {
                                    channel.statistics[`last_temperature_1wire_${t}`] = cell_history[`temperature_1wire_${t}`];
                                }
                            }
                            if(correctTime)
                            {
                                channel.statistics.chart_t.push( [timeMS,cell_history.temperature,cell_history.temperature_1wire_1,cell_history.temperature_1wire_2,cell_history.temperature_1wire_3,cell_history.temperature_1wire_4,cell_history.temperature_1wire_5,cell_history.temperature_1wire_6,cell_history.temperature_1wire_7,cell_history.temperature_1wire_8,cell_history.temperature_1wire_9,cell_history.temperature_1wire_10]);
                            }
                            channel.statistics.countPackage_type_1++;
                        }
                        else if ( typeModBus )
                        {
                            if (lastHistory)
                            {
                                channel.statistics.last_data = cell_history.data_b;
                            }
                            channel.statistics.countPackage_type_9++;
                        }
                        
                    }
                    if(correctTime)
                    {
                        arr_date.push(moment(timeMS).format('LLL' ).replace(',',' ' ));
                    }
                }
                else if (sh02)
                {
                    var type_package = cell_history.type;
                    var type1Wire  = type_package == 1;
                    var typeModBus = type_package == 9;
                    var tz = get_time_zone()*1000;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var validSensor1 = cell_history.sensor_1!==undefined&&typeof cell_history.sensor_1 === 'number';
                    var validSensor2 = cell_history.sensor_2!==undefined&&typeof cell_history.sensor_2 === 'number';
                    var validSensor3 = cell_history.sensor_3!==undefined&&typeof cell_history.sensor_3 === 'number';
                    var validSensor4 = cell_history.sensor_4!==undefined&&typeof cell_history.sensor_4 === 'number';
                    var timeMS = validTime?cell_history.time*1000:undefined;
                    var _item_counter = [timeMS,0,0];
                    var port = 2;
                    channel.statistics.count_full++;
                    var lastHistory = cell_history.time>channel.statistics.last_time;
                    var dangerChannel1 = channel.num_channel == 1 && cell_history.reason == 2;
                    var dangerChannel2 = channel.num_channel == 2 && cell_history.reason == 3;
                    if (validTime&&!_items_counter[timeMS]&&port==2)
                    {
                        channel.statistics.count_all++;

                        if( type1Wire || typeModBus )
                        {
                            if (lastHistory)
                            {
                                channel.statistics.last_temperature = cell_history.temperature;
                                channel.statistics.last_ts = cell_history.ts;
                                channel.statistics.last_time = cell_history.time;
                                channel.statistics.last_ts_rus = moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_time_rus = moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_reason = cell_history.reason;
                                channel.statistics.last_charge = cell_history.charge;
                                channel.statistics.last_sensor= cell_history.sensor;
                                channel.statistics.last_sensor_1 = cell_history.sensor_1;
                                channel.statistics.last_sensor_2 = cell_history.sensor_2;
                                channel.statistics.last_sensor_3 = cell_history.sensor_3;
                                channel.statistics.last_sensor_4 = cell_history.sensor_4;
                                for(var t = 0; t<=10; t++)
                                {
                                    channel.statistics[`last_temperature_1wire_${t}`]  = cell_history[`temperature_1wire_${t}`];
                                }
                            }
                            if(correctTime)
                            {
                                if( dangerChannel1 || dangerChannel2 ) 
                                {
                                    channel.statistics.count_danger++;
                                    arr_value.push( [timeMS,1]);
                                }
                                if (timeMS<minDate)
                                {
                                    minDate = timeMS;
                                    if (channel.num_channel==1) minS = cell_history.sensor_1;
                                    if (channel.num_channel==2) minS = cell_history.sensor_2;
                                }
                                if (timeMS>maxDate)
                                {
                                    maxDate = timeMS;
                                    if (channel.num_channel==1) maxS = cell_history.sensor_1;
                                    if (channel.num_channel==2) maxS = cell_history.sensor_2;
                                }
                                
                                channel.statistics.chart_sensor_new.push( [timeMS+(tz),cell_history.sensor]);
                                
                                channel.statistics.chart.push( [timeMS+tz,cell_history.sensor,0]);
                                channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor,0,cell_history.fcnt]);
                                if (cell_history.temperature!==undefined) channel.statistics.chart_temperature.push( [timeMS,cell_history.temperature]);
                            }
                        }

                        if ( type1Wire )
                        {
                            if (lastHistory)
                            {
                                for(var t = 1; t<=10; t++)
                                {
                                    channel.statistics[`last_temperature_1wire_${t}`] = cell_history[`temperature_1wire_${t}`];
                                }
                            }
                            if(correctTime)
                            {
                                channel.statistics.chart_t.push( [timeMS,cell_history.temperature,cell_history.temperature_1wire_1,cell_history.temperature_1wire_2,cell_history.temperature_1wire_3,cell_history.temperature_1wire_4,cell_history.temperature_1wire_5,cell_history.temperature_1wire_6,cell_history.temperature_1wire_7,cell_history.temperature_1wire_8,cell_history.temperature_1wire_9,cell_history.temperature_1wire_10]);
                            }
                            channel.statistics.countPackage_type_1++;
                        }
                        else if ( typeModBus )
                        {
                            if (lastHistory)
                            {
                                channel.statistics.last_data = cell_history.data_b;
                            }
                            channel.statistics.countPackage_type_9++;
                        }
                        
                    }
                    if(correctTime)
                    {
                        arr_date.push(moment(timeMS).format('LLL' ).replace(',',' ' ));
                    }
                }
                else if (si13rev2)
                {
                    //si13
                    var type_package = cell_history.type;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var validSensor = cell_history.sensor_rate_sum!==undefined&&typeof cell_history.sensor_rate_sum === 'number';
                    var validSensor1 = cell_history.sensor_7!==undefined&&typeof cell_history.sensor_7 === 'number';
                    var validSensor2 = cell_history.sensor_8!==undefined&&typeof cell_history.sensor_8 === 'number';
                    var timeMS = validTime?cell_history.time*1000:undefined;
                    var _item_counter = [timeMS,0,0];
                    var port = 2;
                    channel.statistics.count_full++;
                    if (validTime&&!_items_counter[timeMS]&&port==2)
                    {
                        channel.statistics.count_all++;
                        var ia;
                        var validMer = false;
                        if (cell_history.address!==undefined)
                        {
                            ia = parseInt(cell_history.address,16);
                            if (!isNaN(ia)&&ia==channel.ia)
                            {
                                validMer = true;
                            }
                        }
                        if (type_package == 4 && validMer)
                        {
                            channel.statistics.countPackage_type_4++;
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_sensor_rate_sum=cell_history.sensor_rate_sum;
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                            }
                            if (correctTime&&!_items_counter[timeMS])
                            {
                                _items_counter[timeMS]=true;
                                if (timeMS<minDate)
                                {
                                    minDate = timeMS;
                                    minS = cell_history.sensor_rate_sum;
                                }
                                if (timeMS>maxDate)
                                {
                                    maxDate = timeMS;
                                    maxS = cell_history.sensor_rate_sum;
                                }
                                if (validSensor)
                                {
                                    //ГРАФИК ПОКАЗАНИЙ
                                    channel.statistics.chart.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_rate_sum,0]);

                                    channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_rate_sum,0,cell_history.fcnt]);
                                    
                                    channel.statistics.arr_value_consum_v4.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_rate_1,cell_history.sensor_rate_2,cell_history.sensor_rate_3,cell_history.sensor_rate_4,cell_history.sensor_rate_sum,undefined,undefined]);
                                }
                            }
                            else if( validTime && !_items_counter[timeMS] && validSensor )
                            {
                                _items_counter[timeMS]=true;
                                channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_rate_sum,0,cell_history.fcnt]);
                            }
                        }
                        else if (type_package == 1)
                        {
                            channel.statistics.countPackage_type_1++;
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_time=cell_history.time;
                                if (channel.num_channel==7)channel.statistics.last_sensor=cell_history.sensor_7;
                                if (channel.num_channel==8)channel.statistics.last_sensor=cell_history.sensor_8;
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                            }
                            if (correctTime&&!_items_counter[timeMS])
                            {
                                _items_counter[timeMS]=true;
                                if (timeMS<minDate)
                                {
                                    minDate = timeMS;
                                    if (channel.num_channel==7) minS = cell_history.sensor_7;
                                    if (channel.num_channel==8) minS = cell_history.sensor_8;
                                }
                                if (timeMS>maxDate)
                                {
                                    maxDate = timeMS;
                                    if (channel.num_channel==7) maxS = cell_history.sensor_7;
                                    if (channel.num_channel==8) maxS = cell_history.sensor_8;
                                }
                                    //ГРАФИК ПОКАЗАНИЙ
                                if (channel.num_channel==7&&validSensor1) channel.statistics.chart.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_7,0]);
                                if (channel.num_channel==8&&validSensor2) channel.statistics.chart.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_8,0]);

                                if (channel.num_channel==7&&validSensor1) channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_7,0,cell_history.fcnt]);
                                if (channel.num_channel==8&&validSensor2) channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_8,0,cell_history.fcnt]);

                                
                                if (cell_history.temperature!==undefined) channel.statistics.chart_temperature.push( [timeMS,cell_history.temperature]);
                            }
                            else if( validTime && !_items_counter[timeMS] )
                            {
                                _items_counter[timeMS]=true;
                                if (channel.num_channel==7&&validSensor1) channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_7,0,cell_history.fcnt]);
                                if (channel.num_channel==8&&validSensor2) channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_8,0,cell_history.fcnt]);
                            }
                        }
                        else if (type_package == 2)
                        {
                            channel.statistics.countPackage_type_2++;
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_time=cell_history.time;
                                if (channel.num_channel==7)channel.statistics.last_sensor=cell_history.sensor_7;
                                if (channel.num_channel==8)channel.statistics.last_sensor=cell_history.sensor_8;
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                            }
                            var validNumChannel = (cell_history.num_channel+6)==channel.num_channel;
                            if (correctTime&&!_items_counter[timeMS])
                            {
                                _items_counter[timeMS]=true;
                                if (timeMS<minDate)
                                {
                                    minDate = timeMS;
                                    if (channel.num_channel==7) minS = cell_history.sensor_7;
                                    if (channel.num_channel==8) minS = cell_history.sensor_8;
                                }
                                if (timeMS>maxDate)
                                {
                                    maxDate = timeMS;
                                    if (channel.num_channel==7) maxS = cell_history.sensor_7;
                                    if (channel.num_channel==8) maxS = cell_history.sensor_8;
                                }
                                if (channel.num_channel==7&&validSensor1&&validNumChannel) 
                                {
                                    channel.statistics.chart.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_7,1]);
                                    channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_7,1,cell_history.fcnt]);

                                    
                                    if (!arr_ts_list[timeMS])
                                    {
                                        arr_ts_list[timeMS] = true;
                                        channel.statistics.count_danger++;
                                    }
                                }
                                if (channel.num_channel==8&&validSensor2&&validNumChannel) 
                                {
                                    channel.statistics.chart.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_8,1]);
                                    channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_8,1,cell_history.fcnt]);

                                    if (!arr_ts_list[timeMS])
                                    {
                                        arr_ts_list[timeMS] = true;
                                        channel.statistics.count_danger++;
                                    }
                                }
                                arr_value.push( [timeMS,1]);
                            }
                            else if( validTime && !_items_counter[timeMS] )
                            {
                                _items_counter[timeMS]=true;
                                if (channel.num_channel==7&&validSensor1&&validNumChannel) 
                                {
                                    channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_7,1,cell_history.fcnt]);
                                }
                                if (channel.num_channel==8&&validSensor2&&validNumChannel) 
                                {
                                    channel.statistics.chart_consumption.push( [timeMS+(get_time_zone()*1000),cell_history.sensor_8,1,cell_history.fcnt]);
                                }
                            }
                        }
                        else if( type_package == 6 )
                        {
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                            }
                        }
                    }
                    if(correctTime)
                    {
                        arr_date.push(moment(timeMS).format('LLL' ).replace(',',' ' ));
                    }
                }
                else if ( si21_22rev3 ) 
                {
                    var type_package = cell_history.type;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var validTs = cell_history.ts!==undefined&&cell_history.ts>0;
                    var timeMS = validTime?cell_history.time*1000:undefined;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var port = cell_history.port;
                    channel.statistics.count_full++;
                    var tz = get_time_zone() * 1000;
                    var _item = [cell_history.time,1,0];
                    if(validTs&&!_items_counter[timeMS]&&port==2)
                    {
                        _items_counter[timeMS]=true;
                        channel.statistics.count_all++;
                        if (correctTime)
                        {
                            if( channel.statistics[`countPackage_type_${type_package}`] === undefined ) channel.statistics[`countPackage_type_${type_package}`] = 0;
                            channel.statistics[`countPackage_type_${type_package}`]++;
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_sensor= cell_history.sensor;
                                channel.statistics.last_sensor_1 = cell_history.sensor_1;
                                channel.statistics.last_sensor_2 = cell_history.sensor_2;
                                channel.statistics.last_sensor_3 = cell_history.sensor_3;
                                channel.statistics.last_sensor_4 = cell_history.sensor_4;
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                            }
                            var _item = [cell_history.time,1,0];
                            var dangerChannel = channel.num_channel == cell_history.reason && channel.type_channel == 6;
                            var dangerTemperature = cell_history.reason == 5;
                            var danger = dangerChannel||dangerTemperature;
                            if(!arr_ts_list[timeMS] && correctTime && danger)
                            {
                                arr_ts_list[timeMS] = true;
                                channel.statistics.count_danger++;
                                if(dangerChannel) _item[2] = 1;
                                else if(dangerTemperature) _item[2] = 2;
                                arr_value.push( [timeMS,1]);
                                arr_value_4.push(_item);
                            }
                            channel.statistics.chart_temperature_new.push( [timeMS+tz,cell_history.temperature,cell_history.min_temperature,cell_history.max_temperature, cell_history.limit_exceeded]);
                        }
                        if (cell_history.ts>channel.statistics.last_ts)
                        {
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                        }
                    }
                }
                else if ( si11rev2 )
                {
                    var type_package = cell_history.type;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var validTs = cell_history.ts!==undefined&&cell_history.ts>0;
                    var timeMS = validTime?cell_history.time*1000:undefined;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var port = cell_history.port;

                    var tz = get_time_zone() * 1000;

                    var _item = [cell_history.time,1,0];

                    channel.statistics.count_full++;
                    if(validTs&&!_items_counter[timeMS]&&port==2)
                    {
                        _items_counter[timeMS]=true;
                        channel.statistics.count_all++;
                        if (correctTime)
                        {
                            if( channel.statistics[`countPackage_type_${type_package}`] === undefined ) channel.statistics[`countPackage_type_${type_package}`] = 0;
                            channel.statistics[`countPackage_type_${type_package}`]++;

                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_sensor= cell_history.sensor;
                                channel.statistics.last_sensor_1 = cell_history.sensor_1;
                                channel.statistics.last_sensor_2 = cell_history.sensor_2;
                                channel.statistics.last_sensor_3 = cell_history.sensor_3;
                                channel.statistics.last_sensor_4 = cell_history.sensor_4;
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                            }

                            var _item = [cell_history.time,1,0];
                            var dangerChannel = channel.num_channel == cell_history.reason && channel.type_channel == 6;
                            var danger = dangerChannel;

                            if(!arr_ts_list[timeMS] && correctTime && danger)
                            {
                                arr_ts_list[timeMS] = true;
                                channel.statistics.count_danger++;
                                if(dangerChannel) _item[2] = 1;
                                arr_value.push( [timeMS,1]);
                                // arr_value_4.push(_item);
                            }

                            //channel.statistics.chart_temperature.push( [timeMS,cell_history.temperature]);

                        }
                        if (cell_history.ts>channel.statistics.last_ts)
                        {
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                        }
                    }
                }
                else if ( si12rev2 )
                {
                    var type_package = cell_history.type;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var validTs = cell_history.ts!==undefined&&cell_history.ts>0;
                    var timeMS = validTime?cell_history.time*1000:undefined;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var port = cell_history.port;
                    channel.statistics.count_full++;
                    if(validTs&&!_items_counter[timeMS]&&port==2)
                    {
                        _items_counter[timeMS]=true;
                        channel.statistics.count_all++;
                        if (correctTime)
                        {
                            if( channel.statistics[`countPackage_type_${type_package}`] === undefined ) channel.statistics[`countPackage_type_${type_package}`] = 0;
                            channel.statistics[`countPackage_type_${type_package}`]++;

                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_sensor= cell_history.sensor;
                                channel.statistics.last_sensor_1 = cell_history.sensor_1;
                                channel.statistics.last_sensor_2 = cell_history.sensor_2;
                                channel.statistics.last_sensor_3 = cell_history.sensor_3;
                                channel.statistics.last_sensor_4 = cell_history.sensor_4;
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                                var valid_state_energy = last_state_energy.time === null || cell_history.time > last_state_energy.time;
                                if(valid_state_energy)
                                {
                                    last_state_energy.ts = cell_history.ts;
                                    last_state_energy.time = cell_history.time;
                                    last_state_energy.value = cell_history.state_energy;
                                }
                                var valid_sensor_out_1 = typeof cell_history.sensor_out_1 === 'boolean';
                                var valid_sensor_out_2 = typeof cell_history.sensor_out_2 === 'boolean';
                                var valid_sensor_out_1_lastTime = last_sensor_out_1.time === null || cell_history.time > last_sensor_out_1.time;
                                var valid_sensor_out_2_lastTime = last_sensor_out_2.time === null || cell_history.time > last_sensor_out_2.time;
                                if (valid_sensor_out_1_lastTime && valid_sensor_out_1)
                                {
                                    last_sensor_out_1.ts = cell_history.ts;
                                    last_sensor_out_1.time = cell_history.time;
                                    last_sensor_out_1.value = cell_history.sensor_out_1;
                                }
                                if (valid_sensor_out_2_lastTime && valid_sensor_out_2)
                                {
                                    last_sensor_out_2.ts = cell_history.ts;
                                    last_sensor_out_2.time = cell_history.time;
                                    last_sensor_out_2.value = cell_history.sensor_out_2;
                                }
                            }

                            var _item = [cell_history.time,1,cell_history.reason];
                            // var dangerChannel =  channel.type_channel == 6;
                           var dangerChannel = channel.num_channel == cell_history.reason && channel.type_channel == 6;
                            var danger = dangerChannel;

                            if(!arr_ts_list[timeMS] && correctTime && danger)
                            {
                                arr_ts_list[timeMS] = true;
                                channel.statistics.count_danger++;
                                if(dangerChannel) _item[2] = 1;
                                arr_value.push( [timeMS,1]);
                                arr_value_4.push(_item);
                            }
                        }
                    }
                    else if(validTs&&!_items_counter[timeMS]&&port==5)
                    {
                        _items_counter[timeMS]=true;
                        channel.statistics.count_all++;
                        if (correctTime)
                        {
                            if( channel.statistics[`countPackage_type_${type_package}_port_5`] === undefined ) channel.statistics[`countPackage_type_${type_package}_port_5`] = 0;
                            channel.statistics[`countPackage_type_${type_package}_port_5`]++;

                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_sensor= cell_history.sensor;
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                                var _item = [cell_history.time,1,10];
                                if(cell_history.reason === 1 ) arr_value_4.push(_item);
                                var valid_state_energy = last_state_energy.time === null || cell_history.time > last_state_energy.time;
                                if(valid_state_energy)
                                {
                                    last_state_energy.ts = cell_history.ts;
                                    last_state_energy.time = cell_history.time;
                                    last_state_energy.value = cell_history.state_energy;
                                }
                                var valid_sensor_out_1 = typeof cell_history.sensor_out_1 === 'boolean';
                                var valid_sensor_out_2 = typeof cell_history.sensor_out_2 === 'boolean';
                                var valid_sensor_out_1_lastTime = last_sensor_out_1.time === null || cell_history.time > last_sensor_out_1.time;
                                var valid_sensor_out_2_lastTime = last_sensor_out_2.time === null || cell_history.time > last_sensor_out_2.time;
                                if (valid_sensor_out_1_lastTime && valid_sensor_out_1)
                                {
                                    last_sensor_out_1.ts = cell_history.ts;
                                    last_sensor_out_1.time = cell_history.time;
                                    last_sensor_out_1.value = cell_history.sensor_out_1;
                                }
                                if (valid_sensor_out_2_lastTime && valid_sensor_out_2)
                                {
                                    last_sensor_out_2.ts = cell_history.ts;
                                    last_sensor_out_2.time = cell_history.time;
                                    last_sensor_out_2.value = cell_history.sensor_out_2;
                                }
                            }
                        }
                    }
                    if (cell_history.ts>channel.statistics.last_ts)
                    {
                        channel.statistics.last_ts=cell_history.ts;
                        channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                    }
                }
                else if ( si21 || si22 || si11 || si12 ) 
                {
                    var type_package = cell_history.type;
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var validTs = cell_history.ts!==undefined&&cell_history.ts>0;
                    var timeMS = validTime?cell_history.time*1000:undefined;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                    var port = cell_history.port;
                    channel.statistics.count_full++;
                    if(validTs&&!_items_counter[timeMS]&&port==2)
                    {
                        _items_counter[timeMS]=true;
                        channel.statistics.count_all++;
                        if (type_package == 1 && correctTime)
                        {
                            channel.statistics.countPackage_type_1++;
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_ts=cell_history.ts;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_sensor= cell_history.sensor;
                                channel.statistics.last_sensor_1 = cell_history.sensor_1;
                                channel.statistics.last_sensor_2 = cell_history.sensor_2;
                                channel.statistics.last_sensor_3 = cell_history.sensor_3;
                                channel.statistics.last_sensor_4 = cell_history.sensor_4;
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                            }
                        }
                        else if (type_package == 2 && correctTime)
                        {
                            channel.statistics.countPackage_type_2++;
                            if (cell_history.time>channel.statistics.last_time)
                            {
                                channel.statistics.last_temperature=cell_history.temperature;
                                channel.statistics.last_time=cell_history.time;
                                channel.statistics.last_sensor= cell_history.sensor;
                                channel.statistics.last_charge=cell_history.charge;
                                channel.statistics.last_sensor_1 = cell_history.sensor_1;
                                channel.statistics.last_sensor_2 = cell_history.sensor_2;
                                channel.statistics.last_sensor_3 = cell_history.sensor_3;
                                channel.statistics.last_sensor_4 = cell_history.sensor_4;
                                channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                                channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                            }
                            if (!arr_ts_list[timeMS] && channel.num_channel == cell_history.num_channel && correctTime)
                            {
                                arr_ts_list[timeMS] = true;
                                channel.statistics.count_danger++;
                                arr_value.push( [timeMS,1]);
                            }
                        }
                        else if(cell_history.type==4 && si12 && correctTime)
                        {
                            var valid_state_energy = last_state_energy.time === null || cell_history.time > last_state_energy.time;
                            if(valid_state_energy)
                            {
                                last_state_energy.ts = cell_history.ts;
                                last_state_energy.time = cell_history.time;
                                last_state_energy.value = cell_history.state_energy;
                            }
                        }
                        else if(cell_history.type==5 && si12 && correctTime)
                        {
                            var valid_sensor_out_1 = typeof cell_history.sensor_out_1 === 'boolean';
                            var valid_sensor_out_2 = typeof cell_history.sensor_out_2 === 'boolean';
                            var valid_sensor_out_1_lastTime = last_sensor_out_1.time === null || cell_history.time > last_sensor_out_1.time;
                            var valid_sensor_out_2_lastTime = last_sensor_out_2.time === null || cell_history.time > last_sensor_out_2.time;
                            if (valid_sensor_out_1_lastTime && valid_sensor_out_1)
                            {
                                last_sensor_out_1.ts = cell_history.ts;
                                last_sensor_out_1.time = cell_history.time;
                                last_sensor_out_1.value = cell_history.sensor_out_1;
                            }
                            if (valid_sensor_out_2_lastTime && valid_sensor_out_2)
                            {
                                last_sensor_out_2.ts = cell_history.ts;
                                last_sensor_out_2.time = cell_history.time;
                                last_sensor_out_2.value = cell_history.sensor_out_2;
                            }
                        }
                        if (cell_history.ts>channel.statistics.last_ts)
                        {
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                        }
                    }
                }
                else if ( tp11 )
                {
                    //tp
                    var validTs = cell_history.ts!==undefined && typeof cell_history.ts == 'number' && cell_history.ts>0 ;
                    var validTime = cell_history.ts > ( date.getStart() * 1000 ) && cell_history.ts < ( date.getEnd() * 1000 );
                    if(validTime && !_items_all[cell_history.ts])
                    {
                        var _item = [cell_history.ts, 1, 0];
                        channel.statistics.count_all++;
                        _items_all[cell_history.ts]=true;
                        if (cell_history.type==1)
                        {
                            var valid_sensor_out_1_lastTs=last_sensor_out_1.ts===null||cell_history.ts>last_sensor_out_1.ts;
                            var valid_sensor_out_2_lastTs=last_sensor_out_2.ts===null||cell_history.ts>last_sensor_out_2.ts;
                            var valid_charge_lastTs=last_charge.ts===null||cell_history.ts>last_charge.ts;
                            var valid_type_1_lastTs=last_charge.ts===null||cell_history.ts>last_type_1.ts;
                            channel.statistics.chart_temperature.push( [cell_history.ts,cell_history.temperature]);
                            var checkEvent = false;
                            var sensorEvent = false;
                            var dangerEvent = cell_history.sensor_danger_1||cell_history.sensor_danger_2?true:false;
                            var min_v = parseFloat(channel.min_v);
                            var max_v = parseFloat(channel.max_v);
                            var min = parseFloat(channel.min_normal_v);
                            var max = parseFloat(channel.max_normal_v);
                            var value = cell_history.sensorTP;
                            if (!isNaN(min_v)&&!isNaN(max_v)&&!isNaN(min)&&!isNaN(max))
                            {
                                if (value===0)
                                {
                                    sensorEvent=true;
                                }
                                else if (value<=25&&value>=2)
                                {
                                    var newvalue = my_converter.parse4_20mA(value,min_v,max_v);
                                    if (typeof newvalue === 'number' )
                                    {
                                        if (newvalue<=min||newvalue>=max)
                                        {
                                            sensorEvent = true;
                                        }
                                    }
                                }
                                else
                                {
                                    sensorEvent=true;
                                }
                            }
                            if (sensorEvent&&dangerEvent)
                            {
                                _dangers[cell_history.ts]=true;
                                channel.statistics.count_danger++;
                                _item[2] = 3;
                                _item[3] = 'sensorAndDanger';
                            }
                            else if (sensorEvent)
                            {
                                _dangers[cell_history.ts]=true;
                                channel.statistics.count_danger++;
                                _item[2] = 2;
                                _item[3] = 'sensor';
                            }
                            else if (dangerEvent)
                            {
                                _dangers[cell_history.ts]=true;
                                channel.statistics.count_danger++;
                                _item[2] = 1;
                                _item[3] = 'danger';
                            }
                            if (cell_history.sensorTP>=2&&cell_history.sensorTP<=25&&!_items[cell_history.ts])
                            {
                                _items[cell_history.ts]=true;
                                channel.statistics.count++; 
                                channel.statistics.chart.push( [convert_time(moment(cell_history.ts).unix()),cell_history.sensorTP]);
                                channel.statistics.chart_consumption.push( [convert_time(moment(cell_history.ts).unix()),cell_history.sensorTP,0,cell_history.fcnt]);

                                
                                summ_sensorTP += cell_history.sensorTP;
                                count_sensorTP++;
                            }
                            if (valid_charge_lastTs)
                            {
                                last_charge.ts = cell_history.ts;
                                last_charge.value = cell_history.charge;
                            }
                            if (valid_sensor_out_1_lastTs)
                            {
                                last_sensor_out_1.time = cell_history.time;
                                last_sensor_out_1.ts = cell_history.ts;
                                last_sensor_out_1.value = cell_history.sensor_out_1;
                            }
                            if (valid_sensor_out_2_lastTs)
                            {
                                last_sensor_out_2.ts = cell_history.ts;
                                last_sensor_out_2.time = cell_history.time;
                                last_sensor_out_2.value = cell_history.sensor_out_2;
                            }
                            if (valid_type_1_lastTs)
                            {
                                last_type_1=cell_history;
                            }
                        }
                        else if (cell_history.type==5)
                        {
                            var valid_sensor_out_1=typeof cell_history.sensor_out_1 === 'boolean';
                            var valid_sensor_out_2=typeof cell_history.sensor_out_2 === 'boolean';
                            var valid_sensor_out_1_lastTs=last_sensor_out_1.ts===null||cell_history.ts>last_sensor_out_1.ts;
                            var valid_sensor_out_2_lastTs=last_sensor_out_2.ts===null||cell_history.ts>last_sensor_out_2.ts;
                            var valid_charge_lastTs=last_charge.ts===null||cell_history.ts>last_charge.ts;
                            if (valid_charge_lastTs)
                            {
                                last_charge.ts = cell_history.ts;
                                last_charge.value = cell_history.charge;
                            }
                            if (valid_sensor_out_1&&valid_sensor_out_1_lastTs)
                            {
                                last_sensor_out_1.ts = cell_history.ts;
                                last_sensor_out_1.time = cell_history.time;
                                last_sensor_out_1.value = cell_history.sensor_out_1;
                            }
                            else if (valid_sensor_out_2&&valid_sensor_out_2_lastTs)
                            {
                                last_sensor_out_2.ts = cell_history.ts;
                                last_sensor_out_2.time = cell_history.time;
                                last_sensor_out_2.value = cell_history.sensor_out_2;
                            }
                        }
                        arr_value_4.push(_item);
                    }
                    else if( validTs && !_items_all[cell_history.ts] && cell_history.type == 1 && cell_history.sensorTP>=2 && cell_history.sensorTP<=25 )
                    {
                        _items_all[cell_history.ts]=true;
                        channel.statistics.chart_consumption.push( [convert_time(moment(cell_history.ts).unix()),cell_history.sensorTP,0,cell_history.fcnt]);
                    }
                }
                else if ( tp11rev2 )
                {
                    //tp
                    var vTime = cell_history.time !== undefined && typeof cell_history.time == 'number' && cell_history.time > 0;
                    var validTime = cell_history.time > date.getStart() && cell_history.time < date.getEnd();
                    if(validTime && !_items_all[cell_history.time])
                    {
                        channel.statistics.count_all++;
                        _items_all[cell_history.time] = true;
                        var timeMs = cell_history.time * 1000;
                        if ( cell_history.type == 1 )
                        {
                            var reason = cell_history.reason;
                            var _item = [cell_history.time, 1 ,reason];
                            
                            // var valid_sensor_out_1 = typeof cell_history.sensor_out_1 === 'boolean';
                            // var valid_sensor_out_2 = typeof cell_history.sensor_out_2 === 'boolean';

                            var valid_sensor_out_1_lastTime = last_sensor_out_1.time === null || cell_history.time > last_sensor_out_1.time;
                            var valid_sensor_out_2_lastTime = last_sensor_out_2.time === null || cell_history.time > last_sensor_out_2.time;
                            var valid_charge_lastTime = last_charge.time === null || cell_history.time > last_charge.time;
                            var valid_type_1_lastTime = last_charge.time === null || cell_history.time > last_type_1.time;
                            channel.statistics.chart_temperature.push( [cell_history.time * 1000, cell_history.temperature]);
                            var checkEvent = false;
                            var sensorEvent = false;
                            var dangerEvent = cell_history.sensor_danger_1||cell_history.sensor_danger_2?true:false;
                            var min_v = parseFloat(channel.min_v);
                            var max_v = parseFloat(channel.max_v);
                            var value = cell_history.sensorTP;
                            if(reason != 0 && reason != 5)
                            {
                                 _dangers[cell_history.time] = true;
                                 channel.statistics.count_danger++;
                            }
                            if (cell_history.sensorTP >= 2 && cell_history.sensorTP <= 25 && !_items[cell_history.time] )
                            {
                                _items[cell_history.time]=true;
                                channel.statistics.count++; 
                                channel.statistics.chart.push( [convert_time(cell_history.time),cell_history.sensorTP]);
                                channel.statistics.chart_consumption.push( [convert_time(cell_history.time),cell_history.sensorTP,0,cell_history.fcnt]);

                                
                                channel.statistics.chart_sensor_new.push( [timeMs+(tz*1000),cell_history.sensorTP,cell_history.min_sensor,cell_history.max_sensor, cell_history.limit_exceeded]);
                                summ_sensorTP += cell_history.sensorTP;
                                count_sensorTP++;
                            }
                            if (valid_charge_lastTime)
                            {
                                last_charge.time = cell_history.time;
                                last_charge.value = cell_history.charge;
                            }
                            if (valid_sensor_out_1_lastTime)
                            {
                                last_sensor_out_1.ts = cell_history.ts;
                                last_sensor_out_1.time = cell_history.time;
                                last_sensor_out_1.value = cell_history.sensor_out_1;
                            }
                            if (valid_sensor_out_2_lastTime)
                            {
                                last_sensor_out_2.ts = cell_history.ts;
                                last_sensor_out_2.time = cell_history.time;
                                last_sensor_out_2.value = cell_history.sensor_out_2;
                            }
                            if (valid_type_1_lastTime)
                            {
                                last_type_1 = cell_history;
                            }
                            arr_value_4.push(_item);
                        }
                        else if ( cell_history.type == 5 )
                        {
                            var valid_sensor_out_1 = typeof cell_history.sensor_out_1 === 'boolean';
                            var valid_sensor_out_2 = typeof cell_history.sensor_out_2 === 'boolean';
                            var valid_sensor_out_1_lastTime = last_sensor_out_1.time === null || cell_history.time > last_sensor_out_1.time;
                            var valid_sensor_out_2_lastTime = last_sensor_out_2.time === null || cell_history.time > last_sensor_out_2.time;
                            var valid_charge_lastTime = last_charge.time === null || cell_history.time > last_charge.time;
                            if ( valid_charge_lastTime )
                            {
                                last_charge.time = cell_history.time;
                                last_charge.value = cell_history.charge;
                            }
                            if ( valid_sensor_out_1 && valid_sensor_out_1_lastTime )
                            {
                                last_sensor_out_1.ts = cell_history.ts;
                                last_sensor_out_1.time = cell_history.time;
                                last_sensor_out_1.value = cell_history.sensor_out_1;
                            }
                            else if ( valid_sensor_out_2 && valid_sensor_out_2_lastTime)
                            {
                                last_sensor_out_2.ts = cell_history.ts;
                                last_sensor_out_2.time = cell_history.time;
                                last_sensor_out_2.value = cell_history.sensor_out_2;
                            }
                        }
                    }
                    else if( vTime && !_items_all[cell_history.time] && cell_history.type == 1 && cell_history.sensorTP>=2 && cell_history.sensorTP<=25 )
                    {
                        _items_all[cell_history.time] = true;
                        channel.statistics.chart_consumption.push( [convert_time(cell_history.time),cell_history.sensorTP,0,cell_history.fcnt]);
                    }
                }
                else if ( impulse && cell_history.type==1 )
                {
                    var validTimeHistory = cell_history.time>channel.statistics.last_time;
                    if (validTimeHistory)
                    {
                        channel.statistics.last_temperature=cell_history.temperature;
                        channel.statistics.last_charge=cell_history.charge;
                        channel.statistics.last_time=cell_history.time;
                        channel.statistics.last_fcnt=cell_history.fcnt;
                        channel.statistics.last_sensor= cell_history.sensor;
                        channel.statistics.last_sensor_1 = cell_history.sensor_1;
                        channel.statistics.last_sensor_2 = cell_history.sensor_2;
                        channel.statistics.last_sensor_3 = cell_history.sensor_3;
                        channel.statistics.last_sensor_4 = cell_history.sensor_4;
                    }
                    if (cell_history.ts > channel.statistics.last_ts)
                    {
                        channel.statistics.last_ts = cell_history.ts;
                    }
                }
                else if ( hs )
                {
                      var validTime = cell_history.time!==undefined&&cell_history.time>0;
                      var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                      var timeMS = validTime?cell_history.time*1000:undefined;
                      tz = get_time_zone() * 1000;
                      if(validTime && !_items[timeMS])
                      {
                        _items[timeMS]=true;
                        var reason = cell_history.reason;
                        var _item = [timeMS,1,0];
                        var validTemperature = cell_history.temperature!==undefined;
                        var validDamp = cell_history.damp!==undefined;
                        var validDataTemperature = validTemperature && cell_history.min_temperature !== undefined && cell_history.max_temperature !== undefined;
                        var validDataDamp = validDamp && cell_history.min_sensor !== undefined && cell_history.max_sensor !== undefined;
                        var dangerTemperature = validDataTemperature && (cell_history.min_temperature > cell_history.temperature || cell_history.max_temperature < cell_history.temperature);
                        var dangerDamp =  validDataDamp && ( cell_history.min_sensor > cell_history.damp || cell_history.max_sensor < cell_history.damp );
                        var limit_exceeded_temperature = dangerTemperature || cell_history.reason == 6;
                        var limit_exceeded_damp = dangerDamp || cell_history.reason == 5;
                        channel.statistics.count++;

                        if(correctTime)
                        {
                            if (cell_history.reason!=undefined&&parseInt(cell_history.reason)>1)
                            {
                                channel.statistics.count_danger++;
                            }
                            if (reason!==undefined)
                            {
                                reason = parseInt(reason);
                                if (!isNaN(reason))
                                {
                                    _item[2]=reason;
                                }
                            }
                            arr_value_4.push(_item);
                            channel.statistics.chart_temperature.push( [timeMS,cell_history.temperature]);
                            channel.statistics.chart_temperature_new.push( [timeMS+tz,cell_history.temperature,cell_history.min_temperature,cell_history.max_temperature, limit_exceeded_temperature]);
                            channel.statistics.chart_sensor_new.push( [timeMS+tz,cell_history.damp,cell_history.min_sensor,cell_history.max_sensor, limit_exceeded_damp]);
                        }
                        
                        
                        
                        if (cell_history.ts>channel.statistics.last_ts)
                        {
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                        }
                        if (cell_history.time>channel.statistics.last_time)
                        {
                            channel.statistics.last_min_temperature = cell_history.min_temperature;
                            channel.statistics.last_max_temperature = cell_history.max_temperature;
                            channel.statistics.last_min_sensor = cell_history.min_sensor;
                            channel.statistics.last_max_sensor = cell_history.max_sensor;
                            channel.statistics.last_sensor_in_1 = cell_history.sensor_in_1;
                            channel.statistics.last_sensor_in_2 = cell_history.sensor_in_2;
                            channel.statistics.last_angle=cell_history.angle;
                            channel.statistics.last_damp=cell_history.damp;
                            channel.statistics.last_temperature=cell_history.temperature;
                            channel.statistics.last_charge=cell_history.charge;
                            channel.statistics.last_fcnt=cell_history.fcnt; 
                            channel.statistics.last_reason = cell_history.reason;  
                            channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                            channel.statistics.last_time=cell_history.time;
                        }
                    }
                }
                else if ( um )
                {
                      //надо переделать
                      //   result.last_lux = cell_history.lux;
                      //   result.last_dB = cell_history.dB;
                      //   result.last_CO2 = cell_history.CO2;
                      var validTime = cell_history.time!==undefined&&cell_history.time>0;
                      var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                      var timeMS = validTime?cell_history.time*1000:undefined;
                      tz = get_time_zone() * 1000;
                      if(validTime && !_items[timeMS])
                      {
                        _items[timeMS]=true;
                        var reason = cell_history.reason;
                        var _item = [timeMS,1,0];
                        var validTemperature = cell_history.temperature!==undefined;
                        var validDamp = cell_history.damp!==undefined;

                        var validLux = cell_history.lux!==undefined;
                        var validDB = cell_history.dB!==undefined;
                        var validCO2 = cell_history.CO2!==undefined;

                        var validDataTemperature = validTemperature && cell_history.min_temperature !== undefined && cell_history.max_temperature !== undefined;
                        var validDataDamp = validDamp && cell_history.min_damp !== undefined && cell_history.max_damp !== undefined;

                        var validDataLux = validLux && cell_history.min_lux !== undefined && cell_history.max_lux !== undefined;
                        var validDataDB = validDB && cell_history.min_dB !== undefined && cell_history.max_dB !== undefined;
                        var validDataCO2 = validCO2 && cell_history.min_CO2 !== undefined && cell_history.max_CO2 !== undefined;

                        var dangerTemperature = validDataTemperature && (cell_history.min_temperature > cell_history.temperature || cell_history.max_temperature < cell_history.temperature);
                        var dangerDamp =  validDataDamp && ( cell_history.min_damp > cell_history.damp || cell_history.max_damp < cell_history.damp );

                        var dangerLux =  validDataLux && ( cell_history.min_lux > cell_history.lux || cell_history.max_lux < cell_history.lux );
                        var dangerDB =  validDataDB && ( cell_history.min_dB > cell_history.dB || cell_history.max_dB < cell_history.dB );
                        var dangerCO2 =  validDataCO2 && ( cell_history.min_CO2 > cell_history.CO2 || cell_history.max_CO2 < cell_history.CO2 );

                        var limit_exceeded_temperature = dangerTemperature || cell_history.reason == 6;
                        var limit_exceeded_damp = dangerDamp || cell_history.reason == 5;

                        var limit_exceeded_lux = dangerLux || cell_history.reason == 3;
                        var limit_exceeded_dB = dangerDB || cell_history.reason == 7;
                        var limit_exceeded_CO2 = dangerCO2 || cell_history.reason == 2;
                        channel.statistics.count++;

                        if(correctTime)
                        {
                            if (cell_history.reason!=undefined&&parseInt(cell_history.reason)>1)
                            {
                                channel.statistics.count_danger++;
                            }
                            if (reason!==undefined)
                            {
                                reason = parseInt(reason);
                                if (!isNaN(reason))
                                {
                                    _item[2]=reason;
                                }
                            }
                            arr_value_4.push(_item);
                            //channel.statistics.chart_temperature.push( [timeMS,cell_history.temperature]);
                            channel.statistics.chart_temperature_new.push( [timeMS+tz,cell_history.temperature,cell_history.min_temperature,cell_history.max_temperature, limit_exceeded_temperature]);

                            channel.statistics.chart_damp_new.push( [timeMS+tz,cell_history.damp,cell_history.min_damp,cell_history.max_damp, limit_exceeded_damp]);
                            channel.statistics.chart_lux_new.push( [timeMS+tz,cell_history.lux,cell_history.min_lux,cell_history.max_lux, limit_exceeded_lux]);
                            channel.statistics.chart_dB_new.push( [timeMS+tz,cell_history.dB,cell_history.min_dB,cell_history.max_dB, limit_exceeded_dB]);
                            channel.statistics.chart_CO2_new.push( [timeMS+tz,cell_history.CO2,cell_history.min_CO2,cell_history.max_CO2, limit_exceeded_CO2]);

                            //channel.statistics.chart_sensor_new.push( [timeMS+tz,cell_history.damp,cell_history.min_sensor,cell_history.max_sensor, limit_exceeded_damp]);

                            // channel.statistics.chart_lux.push( [timeMS+tz,cell_history.lux,cell_history.min_sensor,cell_history.max_sensor, limit_exceeded_damp]);
                        }
                        
                        
                        
                        if (cell_history.ts>channel.statistics.last_ts)
                        {
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                        }
                        if (cell_history.time>channel.statistics.last_time)
                        {
                            channel.statistics.last_min_temperature = cell_history.min_temperature;
                            channel.statistics.last_max_temperature = cell_history.max_temperature;

                            channel.statistics.last_min_damp= cell_history.min_damp;
                            channel.statistics.last_max_damp = cell_history.max_damp;
                            
                            channel.statistics.last_min_lux = cell_history.min_lux;
                            channel.statistics.last_max_lux = cell_history.max_lux;

                            channel.statistics.last_min_dB = cell_history.min_dB;
                            channel.statistics.last_max_dB = cell_history.max_dB;
                            
                            channel.statistics.last_min_CO2 = cell_history.min_CO2;
                            channel.statistics.last_max_CO2 = cell_history.max_CO2;

                            channel.statistics.last_min_sensor = cell_history.min_sensor;
                            channel.statistics.last_max_sensor = cell_history.max_sensor;
                            channel.statistics.last_sensor_in_1 = cell_history.sensor_in_1;
                            channel.statistics.last_sensor_in_2 = cell_history.sensor_in_2;
                            channel.statistics.last_angle=cell_history.angle;
                            channel.statistics.last_damp=cell_history.damp;

                            channel.statistics.last_lux=cell_history.lux;
                            channel.statistics.last_dB=cell_history.dB;
                            channel.statistics.last_CO2=cell_history.CO2;

                            channel.statistics.last_temperature=cell_history.temperature;
                            channel.statistics.last_charge=cell_history.charge;
                            channel.statistics.last_fcnt=cell_history.fcnt; 
                            channel.statistics.last_reason = cell_history.reason;  
                            channel.statistics.last_time_rus=moment(timeMS).format('DD.MM.YY HH:mm' );
                            channel.statistics.last_time=cell_history.time;
                        }
                    }
                }
                else if (!_items[cell_history.ts]&&smart&&cell_history.type==1)
                {
                    //smart
                    var checkValidTs=cell_history.ts>(date.getStart()*1000)&&cell_history.ts<(date.getEnd()*1000);
                    if (checkValidTs)
                    {
                        _items[cell_history.ts]=true;
                        var reason = cell_history.reason;
                        var _item = [cell_history.ts,1,0];
                        channel.statistics.count++;
                        if (cell_history.reason!=undefined&&parseInt(cell_history.reason)!==0)
                        {
                            channel.statistics.count_danger++;
                        }
                        if (reason)
                        {
                            reason = parseInt(reason);
                            if (!isNaN(reason)&&reason>0)
                            {
                                _item[2]=reason;
                            }
                        }
                        arr_value_4.push(_item);
                        channel.statistics.chart_temperature.push( [cell_history.ts,cell_history.temperature]);
                    }
                    if (cell_history.ts>channel.statistics.last_ts)
                    {
                        channel.statistics.last_temperature=cell_history.temperature;
                        channel.statistics.last_charge=cell_history.charge;
                        channel.statistics.last_ts=cell_history.ts;
                        channel.statistics.last_fcnt=cell_history.fcnt; 
                        channel.statistics.last_period_connect_minute = cell_history.period_connect_minute;  
                        channel.statistics.last_reason = cell_history.reason;  
                        channel.statistics.last_state_ack = cell_history.state_ack;  
                        channel.statistics.last_state_sensor_0 = cell_history.state_sensor_0; 
                        channel.statistics.last_state_sensor_1 = cell_history.state_sensor_1;
                        channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                    }
                }
                else if (ss0102)
                {
                    var port = cell_history.port;
                    if ( !_items[cell_history.time] && port == 2 )
                    {
                        var checkValidTime=cell_history.time>(date.getStart())&&cell_history.time<(date.getEnd());
                        if(checkValidTime)
                        {
                            _items[cell_history.time]=true;
                            var reason = cell_history.reason;
                            var _item = [cell_history.time*1000,1,0];
                            channel.statistics.count++;
                            var isDanger =  cell_history.reason != 6 && cell_history.reason != 9 && cell_history.reason != 16;
                            if(isDanger)  channel.statistics.count_danger++;
                            if (reason)
                            {
                                reason = parseInt(reason);
                                if (!isNaN(reason)&&reason>0)
                                {
                                    _item[2]=reason;
                                }
                            }
                            arr_value_4.push(_item);
                            channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                        }
                        if (cell_history.ts>channel.statistics.last_ts)
                        {
                            channel.statistics.last_ts=cell_history.ts;
                            channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                        }
                        if (cell_history.time>channel.statistics.last_time)
                        {
                            channel.statistics.last_fcnt=cell_history.fcnt; 
                            channel.statistics.last_time_rus=moment(cell_history.time*1000).format('DD.MM.YY HH:mm' );
                            channel.statistics.last_time = cell_history.time;
                            channel.statistics.last_reason = cell_history.reason;
                            channel.statistics.last_status_fog = cell_history.status_fog;
                            channel.statistics.last_status_fire = cell_history.status_fire;
                            channel.statistics.last_status_test = cell_history.status_test;
                            channel.statistics.last_status_guard = cell_history.status_guard;
                            channel.statistics.last_status_faulm = cell_history.status_faulm;
                            channel.statistics.last_status_alarm = cell_history.status_alarm;
                            channel.statistics.last_status_detach = cell_history.status_detach;
                            channel.statistics.last_status_common = cell_history.status_common;
                            channel.statistics.last_current_mV = cell_history.current_mV;
                            channel.statistics.last_current_mA = cell_history.current_mA;
                            channel.statistics.last_temperature = cell_history.temperature;
                            channel.statistics.last_charge = cell_history.charge;
                            channel.statistics.last_charge2 = cell_history.charge2;
                            channel.statistics.last_battery_select_1 = cell_history.battery_select_1;
                            channel.statistics.last_battery_select_2 = cell_history.battery_select_2;
                            channel.statistics.last_battery_persent_1 = cell_history.battery_persent_1;
                            channel.statistics.last_battery_persent_2 = cell_history.battery_persent_2;
                        }
                    }
                }
                else if (!_items[cell_history.time]&&smartRev2&&cell_history.type==1)
                {
                    //smart
                    var checkValidTime=cell_history.time>(date.getStart())&&cell_history.time<(date.getEnd());
                    if (checkValidTime)
                    {
                        _items[cell_history.time]=true;
                        var reason = cell_history.reason;
                        var _item = [cell_history.time*1000,1,0];
                        channel.statistics.count++;
                        if (cell_history.reason!=undefined&&parseInt(cell_history.reason)!==0)
                        {
                            channel.statistics.count_danger++;
                        }
                        if (reason)
                        {
                            reason = parseInt(reason);
                            if (!isNaN(reason)&&reason>0)
                            {
                                _item[2]=reason;
                            }
                        }
                        arr_value_4.push(_item);
                        channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                    }
                    if (cell_history.ts>channel.statistics.last_ts)
                    {
                        channel.statistics.last_ts=cell_history.ts;
                        channel.statistics.last_ts_rus=moment(cell_history.ts).format('DD.MM.YY HH:mm' );
                    }
                    if (cell_history.time>channel.statistics.last_time)
                    {
                        channel.statistics.last_angle=cell_history.angle;
                        channel.statistics.last_temperature=cell_history.temperature;
                        channel.statistics.last_charge=cell_history.charge;
                        channel.statistics.last_time=cell_history.time;
                        channel.statistics.last_fcnt=cell_history.fcnt; 
                        channel.statistics.last_period_connect_minute = cell_history.period_connect_minute;  
                        channel.statistics.last_reason = cell_history.reason;  
                        channel.statistics.last_state_ack = cell_history.state_ack;  
                        channel.statistics.last_state_sensor_0 = cell_history.state_sensor_0; 
                        channel.statistics.last_state_sensor_1 = cell_history.state_sensor_1;
                        channel.statistics.last_time_rus=moment(cell_history.time*1000).format('DD.MM.YY HH:mm' );
                    }
                }
                else if ( cell_history.type==2 && channelDanger )
                {
                    channel.statistics.count_danger_full++;

                    
                    var validTime = cell_history.time!==undefined&&cell_history.time>0;
                    var timeMs = validTime&&cell_history.time * 1000;
                    var correctTime = validTime&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();

                    if (cell_history.ts>channel.statistics.last_ts)
                    {
                        channel.statistics.last_ts=cell_history.ts;
                    }
                    if (cell_history.time>channel.statistics.last_time)
                    {
                        channel.statistics.last_time=cell_history.time;
                        channel.statistics.last_charge=cell_history.charge;
                        channel.statistics.last_sensor=cell_history.sensor;
                        channel.statistics.last_sensor_1 = cell_history.sensor_1;
                        channel.statistics.last_sensor_2 = cell_history.sensor_2;
                        channel.statistics.last_sensor_3 = cell_history.sensor_3;
                        channel.statistics.last_sensor_4 = cell_history.sensor_4;
                    }
                    
                    if (!arr_ts_list[timeMs] && channel.num_channel == cell_history.num_channel && correctTime)
                    {
                        arr_ts_list[timeMs] = true;
                        channel.statistics.count_danger++;
                        arr_value.push( [timeMs,1]);
                    }
                }
                var validCorrectTime = cell_history.time!==undefined&&cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd();
                if (validCorrectTime&&cell_history.type==1&&(si11||si21||si12||si22||si21))
                {
                    channel.statistics.chart.push( [convert_time(cell_history.time)*1000,cell_history.sensor]);
                    channel.statistics.chart_consumption.push( [convert_time(cell_history.time)*1000,cell_history.sensor,0,cell_history.fcnt]);
                    

                    if (cell_history.time<minDate)
                    {
                        minDate = cell_history.time;
                        minS = cell_history.sensor;
                    }
                    if (cell_history.time>maxDate)
                    {
                        maxDate = cell_history.time;
                        maxS = cell_history.sensor;
                    }
                    if (cell_history.time!=undefined&&cell_history.sensor!=undefined)
                    {
                        tempArr.push( [cell_history.time,cell_history.sensor]);
                        temp[cell_history.time]=cell_history.sensor;
                    }
                    else if (cell_history.time!=undefined)
                    {
                        console.log('Error 1294' );
                    }
                    channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                } 
                else if (validCorrectTime&&(si21_22rev3||si11rev2||si12rev2))
                {
                    channel.statistics.chart.push( [convert_time(cell_history.time)*1000,cell_history.sensor]);
                    channel.statistics.chart_consumption.push( [convert_time(cell_history.time)*1000,cell_history.sensor,0,cell_history.fcnt]);
                    

                    if (cell_history.time<minDate)
                    {
                        minDate = cell_history.time;
                        minS = cell_history.sensor;
                    }
                    if (cell_history.time>maxDate)
                    {
                        maxDate = cell_history.time;
                        maxS = cell_history.sensor;
                    }
                    if (cell_history.time!=undefined&&cell_history.sensor!=undefined)
                    {
                        tempArr.push( [cell_history.time,cell_history.sensor]);
                        temp[cell_history.time]=cell_history.sensor;
                    }
                    else if (cell_history.time!=undefined)
                    {
                        console.log('Error 1294' );
                    }
                    channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                }
                else if( cell_history.time!==undefined && cell_history.type==1&&(si11||si21||si12||si22||si21) )
                {
                    _items_all[cell_history.time] = true;
                    channel.statistics.chart_consumption.push( [convert_time(cell_history.time)*1000,cell_history.sensor,0,cell_history.fcnt]);
                }
                else if ( cell_history.ts > ( date.getStart() * 1000 ) && cell_history.ts < ( date.getEnd() * 1000 ) && cell_history.type == 1 && ( td11 ) )
                {
                   channel.statistics.chart_temperature.push( [cell_history.ts, cell_history.temperature] );
                }
                else if (cell_history.time>=date.getStart()&&cell_history.time<=date.getEnd()&&cell_history.type==1&&device.device_type==9)
                {
                    if (!_items_1[cell_history.time])
                    {
                        _items_1[cell_history.time]=true;
                        channel.statistics.chart.push( [convert_time(cell_history.time)*1000,cell_history.sensorKB]);

                        channel.statistics.chart_consumption.push( [convert_time(cell_history.time)*1000,cell_history.sensorKB,0,cell_history.fcnt]);
                        
                        if (cell_history.time<minDate)
                        {
                            minDate = cell_history.time;
                            minS = cell_history.sensorKB;
                        }
                        if (cell_history.time>maxDate)
                        {
                            maxDate = cell_history.time;
                            maxS = cell_history.sensorKB;
                        }
                        if (cell_history.time!=undefined&&cell_history.sensorKB!=undefined)
                        {
                            tempArr.push( [cell_history.time,cell_history.sensorKB]);
                            temp[cell_history.time]=cell_history.sensorKB;
                        }
                        else if (cell_history.time!=undefined)
                        {
                            console.log('Error 1294' );
                        }
                       channel.statistics.chart_temperature.push( [cell_history.time*1000,cell_history.temperature]);
                   }
                }
                else if( cell_history.time!==undefined &&cell_history.type==1&&device.device_type==9 && !_items_1[cell_history.time])
                {
                    _items_1[cell_history.time]=true;
                    channel.statistics.chart_consumption.push( [convert_time(cell_history.time)*1000,cell_history.sensorKB,0,cell_history.fcnt]);
                }
                if (cell_history.ts>(date.getStart()*1000)&&cell_history.ts<(date.getEnd()*1000)&&!si13rev2)
                {
                    connect.push({date: cell_history.ts,rssi: my_converter.round_size(cell_history.rssi,2),snr:my_converter.round_size(cell_history.snr,2)});
                    arr_date.push(moment(cell_history.ts).format('LLL' ).replace(',',' ' ));
                    arr_rssi.push(my_converter.round_size(cell_history.rssi,2));
                    arr_snr.push(my_converter.round_size(cell_history.snr,2));
                    snr.val+=cell_history.snr;snr.count++;
                    rssi.val+=cell_history.rssi;rssi.count++;  
                }
                
            }
            if (tp11)
            {
                var ts_arr = new Array();
                var validLastTsType1=last_type_1!=undefined&&last_type_1.ts>0;
                var validLastTsSensorOut1=last_sensor_out_1!=undefined&&last_sensor_out_1.ts;
                var validLastTsSensorOut2=last_sensor_out_2!=undefined&&last_sensor_out_2.ts;
                var validLastTsCharge=last_charge!=undefined&&last_charge.ts;
                if (validLastTsType1)
                {
                    ts_arr.push(last_type_1.ts);
                    if (!validLastTsSensorOut1)
                    {
                        channel.statistics.last_sensor_out_1 = last_type_1.sensor_out_1;
                    }
                    if (!validLastTsSensorOut2)
                    {
                        channel.statistics.last_sensor_out_2 = last_type_1.sensor_out_2;
                    }
                    if (!validLastTsCharge)
                    {
                        channel.statistics.last_charge = last_type_1.charge;
                    }
                    channel.statistics.last_sensorTP = last_type_1.sensorTP;
                    channel.statistics.last_temperature = last_type_1.temperature;
                    channel.statistics.last_sensor_danger_1 = last_type_1.sensor_danger_1;
                    channel.statistics.last_sensor_danger_2 = last_type_1.sensor_danger_2;
                    channel.statistics.last_type_powered = last_type_1.type_powered;
                }
                if (validLastTsSensorOut1)
                {
                    ts_arr.push(last_sensor_out_1.ts);
                    if (validLastTsType1&&last_type_1.ts>last_sensor_out_1.ts)
                    {
                        channel.statistics.last_sensor_out_1 = last_type_1.sensor_out_1;
                    }
                    else
                    {
                        channel.statistics.last_sensor_out_1 = last_sensor_out_1.value;
                    }
                }
                if (validLastTsSensorOut2)
                {
                    ts_arr.push(last_sensor_out_2.ts);
                    if (validLastTsType1&&last_type_1.ts>last_sensor_out_2.ts)
                    {
                        channel.statistics.last_sensor_out_2 = last_type_1.sensor_out_2;
                    }
                    else
                    {
                        channel.statistics.last_sensor_out_2 = last_sensor_out_2.value;
                    }
                }
                if (validLastTsCharge)
                {
                    ts_arr.push(last_charge.ts);
                    if (validLastTsType1&&last_type_1.ts>last_charge.ts)
                    {
                        channel.statistics.last_charge = last_type_1.charge;
                    }
                    else
                    {
                        channel.statistics.last_charge = last_charge.value;
                    }
                }
                for(var i = 0; i<ts_arr.length;i++)
                {
                    if (!channel.statistics.last_ts||channel.statistics.last_ts<ts_arr[i])
                    {
                        channel.statistics.last_ts = ts_arr[i];
                    }
                }
                channel.statistics.avgSensorTP = Math.round(((summ_sensorTP/count_sensorTP)*1000))/1000;
            } 
            else if (tp11rev2)
            {
                var time_arr = new Array();
                var validLastTimeType1 = last_type_1 != undefined && last_type_1.time > 0;
                var validLastTimeSensorOut1 = last_sensor_out_1 != undefined && last_sensor_out_1.time;
                var validLastTimeSensorOut2 = last_sensor_out_2 != undefined && last_sensor_out_2.time;
                var validLastTimeCharge = last_charge != undefined && last_charge.time;
                if ( validLastTimeType1 )
                {
                    time_arr.push(last_type_1.time);
                    if (!validLastTimeSensorOut1)
                    {
                        channel.statistics.last_sensor_out_1 = last_type_1.sensor_out_1;
                    }
                    if (!validLastTimeSensorOut2)
                    {
                        channel.statistics.last_sensor_out_2 = last_type_1.sensor_out_2;
                    }
                    if (!validLastTimeCharge)
                    {
                        channel.statistics.last_charge = last_type_1.charge;
                    }
                    channel.statistics.last_sensorTP = last_type_1.sensorTP;
                    channel.statistics.last_temperature = last_type_1.temperature;
                    channel.statistics.last_sensor_danger_1 = last_type_1.sensor_danger_1;
                    channel.statistics.last_sensor_danger_2 = last_type_1.sensor_danger_2;
                    channel.statistics.last_type_powered = last_type_1.type_powered;
                }
                if ( validLastTimeSensorOut1 )
                {
                    time_arr.push( last_sensor_out_1.time );
                    if ( validLastTimeType1 && last_type_1.time > last_sensor_out_1.time )
                    {
                        channel.statistics.last_sensor_out_1 = last_type_1.sensor_out_1;
                    }
                    else
                    {
                        channel.statistics.last_sensor_out_1 = last_sensor_out_1.value;
                    }
                }
                if ( validLastTimeSensorOut2 )
                {
                    time_arr.push( last_sensor_out_2.time );
                    if (validLastTimeType1&&last_type_1.time>last_sensor_out_2.time)
                    {
                        channel.statistics.last_sensor_out_2 = last_type_1.sensor_out_2;
                    }
                    else
                    {
                        channel.statistics.last_sensor_out_2 = last_sensor_out_2.value;
                    }
                }
                if ( validLastTimeCharge )
                {
                    time_arr.push( last_charge.time );
                    if ( validLastTimeType1 && last_type_1.time > last_charge.time )
                    {
                        channel.statistics.last_charge = last_type_1.charge;
                    }
                    else
                    {
                        channel.statistics.last_charge = last_charge.value;
                    }
                }
                for( var i = 0; i < time_arr.length; i++ )
                {
                    if ( !channel.statistics.last_time || channel.statistics.last_time < time_arr[i] )
                    {
                        channel.statistics.last_time = time_arr[i];
                    }
                }
                channel.statistics.avgSensorTP = Math.round( ( ( summ_sensorTP / count_sensorTP ) * 1000 ) ) / 1000;
            }
            if (channel.type_channel==6)
            {

            }
            else
            {
                fcnt = arr_date.length;
                var tempData = [];
                var tempTime =minDate;
                var block = 0;
                while(tempTime<=maxDate)
                {
                    if (temp[tempTime]!=undefined&&temp[tempTime+HOUR_S]!=undefined)
                    {
                        try
                        {
                            var resultV=temp[tempTime+HOUR_S]-temp[tempTime];
                            if (resultV>0)
                            {
                                tempData.push( [(convert_time(tempTime)+HOUR_S)*1000,resultV]);  
                            }
                        }
                        catch(err)
                        {
                            tempData.push( [(convert_time(tempTime)+HOUR_S)*1000,0]);
                        }
                    }
                    else if ((convert_time(tempTime)+HOUR_S)*1000<=new Date().getTime())
                    {
                        tempData.push( [(convert_time(tempTime)+HOUR_S)*1000,0]);
                    }
                    tempTime=tempTime+HOUR_S;
                }    
                for (var i =tempArr.length-1;i>=0;i--)
                {
                    if (tempArr[i][0]>=block)
                    {
                        var temp_next = tempArr[i][0]+HOUR_S;
                        if (temp[temp_next]!=undefined)
                        {
                            if ((temp_next-block)%HOUR_S==0||block==0)
                            {
                                arr_value.push( [(convert_time(temp_next))*1000,temp[temp_next]-tempArr[i][1]]);
                                block = temp_next;
                                delete temp[temp_next];
                            }
                        }
                        else
                        {
                            arr_value.push( [convert_time(temp_next)*1000,0]);
                            block = temp_next;
                        }
                    }
                }
                if (device.device_type!=4)
                {
                    arr_value = tempData;
                }
                channel.statistics.chart.sort(function(a,b){
                    return a[0]-b[0];
                });
                channel.statistics.chart_consumption.sort(function(a,b){
                    return a[0]-b[0];
                });
            }
            if( si12 || mbus1 )
            {
                channel.statistics.last_sensor_out_1 = last_sensor_out_1.value;
                channel.statistics.last_sensor_out_2 = last_sensor_out_2.value;
                channel.statistics.last_state_energy = last_state_energy.value;
            }
            arr_value.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.arr_value_events.sort(function(a,b){
                return a[0]-b[0];
            });
            arr_value_4.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.arr_power_profile.sort(function(a,b){
                return a.date_1-b.date_1;
            });
            channel.statistics.arr_value_consum.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.arr_value_consum_v4.sort(function(a,b){
                return a[0]-b[0];
            });
            
            channel.statistics.chart_temperature.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.chart_damp_new.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.chart_lux_new.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.chart_dB_new.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.chart_CO2_new.sort(function(a,b){
                return a[0]-b[0];
            });

            channel.statistics.chart_temperature_new.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.chart_sensor_new.sort(function(a,b){
                return a[0]-b[0];
            });
            channel.statistics.chart_t.sort(function(a,b){
                return a[0]-b[0];
            });
            for (var i = 0 ; i< channel.statistics.chart_t.length;i++)
            {
                channel.statistics.chart_t[i][0]= channel.statistics.chart_t[i][0]+(1000*get_time_zone());
            }
            for (var i = 0 ; i< channel.statistics.chart_temperature.length;i++)
            {
                if (device.device_type!=12) channel.statistics.chart_temperature[i][0]= channel.statistics.chart_temperature[i][0]+(1000*get_time_zone());
            }
            for (var i = 0 ; i< arr_value.length;i++)
            {
                
                arr_value[i][0]= arr_value[i][0]+(get_time_zone()*1000);
                
            }
            for (var i = 0 ; i< arr_value_4.length;i++)
            {
                if ( device.device_type == 9 )
                {
                    arr_value_4[i][0] = arr_value_4[i][0] * 1000 + ( 1000 * get_time_zone() );
                }
                else if ( device.device_type == 15 )
                {
                    arr_value_4[i][0] = arr_value_4[i][0] + ( 1000 * get_time_zone() );
                }
                else if ( device.device_type == 12 || device.device_type == 24 || device.device_type == 27 )
                {
                    arr_value_4[i][0] = arr_value_4[i][0] * 1000;
                }
                else if ( device.device_type == 13 )
                {
                    arr_value_4[i][0] = arr_value_4[i][0] * 1000 + ( 1000 * get_time_zone() );
                } 
                else if ( smart || smartRev2 || hs || um || ss0102 )
                {
                    arr_value_4[i][0] = arr_value_4[i][0] + ( 1000 * get_time_zone() );
                }
                else if ( tp11 )
                {
                    arr_value_4[i][0] = arr_value_4[i][0] + get_time_zone()*1000;
                }
                else if ( tp11rev2 )
                {
                    arr_value_4[i][0] = arr_value_4[i][0] * 1000 + ( 1000 * get_time_zone() );
                }
                else if (td11)
                {
                    arr_value_4[i][0] = arr_value_4[i][0] + get_time_zone()*1000;
                }
                else if (td11rev2)
                {
                    arr_value_4[i][0] = arr_value_4[i][0] * 1000 + ( 1000 * get_time_zone() );
                }
                else
                {
                    arr_value_4[i][0] = arr_value_4[i][0] * 1000 + ( 1000 * get_time_zone() );
                }
                
            }
            if (channel.history.length>0)
            {
                channel.statistics.avgTemperatur=Math.round(((summ_t/channel.history.length)*10))/10;
            }
            else
            {
                channel.statistics.avgTemperatur = false;
            }
            if (device.device_type==9)
            {
                channel.statistics.consumed = maxS-minS;
                channel.statistics.start_sensorKB = minS;
                channel.statistics.end_sensorKB = maxS;
            }
            else if (si13 || si13rev2)
            {
                if(impulse)
                {
                    channel.statistics.consumed = my_converter.round_size(((maxS-minS)/this.select_channel_temp.division)*kt,2);
                    channel.statistics.start_sensor = my_converter.round_size((((this.select_channel_temp.init_value*this.select_channel_temp.division)+minS)/this.select_channel_temp.division)*kt,3);
                    channel.statistics.end_sensor = my_converter.round_size((((this.select_channel_temp.init_value*this.select_channel_temp.division)+maxS)/this.select_channel_temp.division)*kt,3);
                }
                else
                {
                    channel.statistics.consumed = maxS-minS;
                    channel.statistics.start_sensor = minS;
                    channel.statistics.end_sensor = maxS;
                }
            }
            else if ( device.device_type == 12 || device.device_type == 24 || device.device_type == 27 )
            {
                
                channel.statistics.consumed = maxS-minS;
                channel.statistics.start_value = minS;
                channel.statistics.end_value = maxS;
                channel.statistics.avgTemperatur=Math.round(((summ_t/count_t)*10))/10;
            }
            else if (device.device_type==4)
            {
                channel.statistics.avgTemperatur=Math.round(((summ_t/count_t)*10))/10;
            }
            else
            {
                channel.statistics.consumed = my_converter.round_size(((maxS-minS)/this.select_channel_temp.division)*kt,2);
                channel.statistics.start_sensor = my_converter.round_size((((this.select_channel_temp.init_value*this.select_channel_temp.division)+minS)/this.select_channel_temp.division)*kt,3);
                channel.statistics.end_sensor = my_converter.round_size((((this.select_channel_temp.init_value*this.select_channel_temp.division)+maxS)/this.select_channel_temp.division)*kt,3);
            }
            
            channel.statistics.last_time_rus=channel.type_channel==14?moment.unix(channel.statistics.last_time).utc().format('DD.MM.YY HH:mm' ):moment.unix(channel.statistics.last_time).format('DD.MM.YY HH:mm' );
            channel.statistics.fcnt = fcnt;
            channel.statistics.avr_snr = my_converter.round_size((snr.val/snr.count),2);
            channel.statistics.avr_rssi = my_converter.round_size((rssi.val/rssi.count),2);
            channel.statistics.arr_date = arr_date;
            channel.statistics.arr_rssi = arr_rssi;
            channel.statistics.arr_snr = arr_snr;
            channel.statistics.connect = connect;
            channel.statistics.arr_value = arr_value;
            channel.statistics.arr_value_4 = arr_value_4;
            channel.statistics.type_channel = channel.type_channel;
            channel.statistics.dangers = _dangers;
        }
        catch (err)
        {
            return false;
        }
    }
}
class cell_history
{
    constructor(mess,data,num_sensor,dt,version)
    {
        this.version = version;
        this.ts=mess.ts;
        this.ack=mess.ack;
        this.fcnt=mess.fcnt;
        this.port=mess.port;
        this.freq=mess.freq;
        this.dr=mess.dr;
        this.temperature=data.temperature;
        this.temperature_2=data.temperature_2;
        this.sensor_1=data.sensors.sensor_1;
        this.sensor_2=data.sensors.sensor_2;
        this.sensor_3=data.sensors.sensor_3;
        this.sensor_4=data.sensors.sensor_4;
        this.sensor_5=data.sensor_5;
        this.sensor_6=data.sensor_6;
        this.sensor_7=data.sensor_7;
        this.sensor_8=data.sensor_8;
        this.sensor_9=data.sensor_9;
        this.sensor_10=data.sensor_10;
        this.sensor_11=data.sensor_11;
        this.sensor_12=data.sensor_12;
        this.rssi=mess.rssi;
        this.snr=mess.snr;
        this.charge=data.charge;
        this.charge2=data.charge2;
        this.switch_device=data.switch_device;
        this.time=data.time;
        this.num_channel = data.num_channel;
        this.sensor=data.sensors['sensor_'+num_sensor];
        this.type = data.type_package;
        
        this.sensorKB = data.sensorKB;
        
        this.state_tamper=data.state_tamper;
        this.state_display=data.state_display;
        this.state_security=data.state_security;
        this.leaking = data.leaking;
        this.breakthrough = data.breakthrough;
        this.reason=data.reason;
        this.hall_1=data.hall_1;
        this.hall_2=data.hall_2;
        
        this.limit_exceeded=data.limit_exceeded;
        this.min_temperature=data.min_temperature;
        this.min_damp=data.min_damp;
        this.max_damp=data.max_damp;
        this.min_lux=data.min_lux;
        this.max_lux=data.max_lux;
        this.min_dB=data.min_dB;
        this.max_dB=data.max_dB;
        this.min_CO2=data.min_CO2;
        this.max_CO2=data.max_CO2;
        this.max_temperature=data.max_temperature;
        this.min_sensor=data.min_sensor;
        this.max_sensor=data.max_sensor;

        
        
        this.dt = dt;
        
        this.type_activation=data.type_activation;
        this.state_ack=data.state_ack;
        this.period_connect_minute=data.period_connect_minute;
        this.collection_period_minute=data.collection_period_minute;
        this.time_zone_minute=data.time_zone_minute;
        this.type_powered=data.type_powered;
        this.sensor_danger_1=data.sensor_danger_1;
        this.sensor_danger_2=data.sensor_danger_2;
        this.sensor_out_1=data.sensor_out_1;
        this.sensor_out_2=data.sensor_out_2;
        this.num_out_channel=data.num_out_channel;
        
        this.sensor_in_1=data.sensor_in_1;
        this.sensor_in_2=data.sensor_in_2;
        this.sensorTP=data.sensorTP;
        this.state_sensor_0=data.state_sensor_0;
        this.state_sensor_1=data.state_sensor_1;
        
        
        this.count_rate_active = data.count_rate_active;
        this.rate_active = data.rate_active;
        this.kt = data.kt;
        this.note_1 = data.note_1;
        this.note_2 = data.note_2;
        this.event = data.event;
        this.state = data.state;
        this.type_in = data.type_in;
        this.type2 = data.type2;
        this.result = data.result;
        this.sensor_rate_0 = data.sensor_rate_0;
        this.sensor_rate_1 = data.sensor_rate_1;
        this.sensor_rate_2 = data.sensor_rate_2;
        this.sensor_rate_3 = data.sensor_rate_3;
        this.sensor_rate_4 = data.sensor_rate_4;
        this.sensor_rate_sum = data.sensor_rate_sum;

        this.status_fog = data.status_fog ;
        this.status_fire = data.status_fire ;
        this.status_test = data.status_test ;
        this.status_guard = data.status_guard ;
        this.status_faulm = data.status_faulm ;
        this.status_alarm = data.status_alarm ;
        this.status_detach = data.status_detach ;
        this.status_common = data.status_common ;
        this.current_mV = data.current_mV ;
        this.current_mA = data.current_mA ;
        this.battery_select_1 = data.battery_select_1 ;
        this.battery_select_2 = data.battery_select_2 ;
        this.battery_persent_1 = data.battery_persent_1 ;
        this.battery_persent_2 = data.battery_persent_2 ;
        
        this.in_move = data.in_move;
        this.angle = data.angle;
        this.led_duty = data.led_duty;
        this.damp = data.damp;
        this.lux = data.lux;
        this.dB = data.dB;
        this.CO2 = data.CO2;
        this.coord_status = data.coord_status;
        this.lat = data.lat;
        this.lng = data.lng;
        this.dir = data.dir;
        this.speed = data.speed;
        this.alt = data.alt;
        this.sat_visible = data.sat_visible;
        this.sat_used = data.sat_used;
        this.alarm = data.alarm;


        this.note_1 = data.note_1;
        this.note_2 = data.note_2;
        this.network_address = data.network_address;
        this.time_zone = data.time_zone;
        this.period_reconnection_h = data.period_reconnection_h;
        this.flag_event = data.flag_event;
        this.flag_helf_hour = data.flag_helf_hour;
        this.flag_ack = data.flag_ack;
        this.limit_power = data.limit_power;
        this.accumulation_period_info = data.accumulation_period_info;
        this.accumulation_period_day_info = data.accumulation_period_day_info;
        this.accumulation_period_month_info = data.accumulation_period_month_info;
        this.accumulation_period_readings = data.accumulation_period_readings;
        this.accumulation_period_day_readings = data.accumulation_period_day_readings;
        this.accumulation_period_month_readings = data.accumulation_period_month_readings;
        this.accumulation_period_instant = data.accumulation_period_instant;
        this.accumulation_period_day_instant = data.accumulation_period_day_instant;
        this.accumulation_period_month_instant = data.accumulation_period_month_instant;
        this.tariff_schedule_season_number = data.tariff_schedule_season_number;
        this.tariff_schedule_code = data.tariff_schedule_code;
        for(var i = 1; i<=15; i++)
        {
            this[`tariff_schedule_minute_end_${i}_zone`] = data[`tariff_schedule_minute_end_${i}_zone`];
            this[`tariff_schedule_hour_end_${i}_zone`] = data[`tariff_schedule_hour_end_${i}_zone`];
            this[`tariff_schedule_number_${i}_zone`] = data[`tariff_schedule_number_${i}_zone`];
        }
        for(var i = 1; i<=10; i++)
        {
            this[`temperature_1wire_${i}`] = data[`temperature_1wire_${i}`];
        }
        this.version_soft_device = data.version_soft_device;
        this.code_error_1 = data.code_error_1;
        this.code_error_2 = data.code_error_2;
        this.code_error_3 = data.code_error_3;
        this.code_error_4 = data.code_error_4;
        this.code_error_5 = data.code_error_5;
        this.diagnostic_codes = data.diagnostic_codes;
        this.location_description = data.location_description;
        this.version_module_electronic = data.version_module_electronic;
        this.version_parameterization = data.version_parameterization;
        this.flag_translation_time = data.flag_translation_time;
        this.flag_relay = data.flag_relay;
        this.state_relay = data.state_relay;
        this.info_radiomodule = data.info_radiomodule;
        this.nomenal_voltage = data.nomenal_voltage;
        this.nomenal_current = data.nomenal_current;
        this.code_model = data.code_model;
        this.maximal_current = data.maximal_current;
        this.limit_active_power = data.limit_active_power;
        this.time_minute_averages_power = data.time_minute_averages_power;
        this.mode_measuring_power = data.mode_measuring_power;
        this.time_minute_delay_automatic_switching_relay = data.time_minute_delay_automatic_switching_relay;


        this.selected_d_archive = data.selected_d_archive;
        this.selected_m_archive = data.selected_m_archive;
        this.selected_y_archive = data.selected_y_archive;
        this.cumulative_energy_summary = data.cumulative_energy_summary;
        this.cumulative_energy_rate_1 = data.cumulative_energy_rate_1;
        this.cumulative_energy_rate_2 = data.cumulative_energy_rate_2;
        this.cumulative_energy_rate_3 = data.cumulative_energy_rate_3;
        this.cumulative_energy_rate_4 = data.cumulative_energy_rate_4;

        this.count_automatic_switching_relay = data.count_automatic_switching_relay;
        for(var i = 1; i<=31; i++)
        {
            this[`code_page_indication_${i}`] = data[`code_page_indication_${i}`] ;
            this[`time_seconds_show_page_indication_${i}`] = data[`time_seconds_show_page_indication_${i}`];
        }
        this.voltage_A = data.voltage_A;
        this.voltage_B = data.voltage_B;
        this.voltage_C = data.voltage_C;
        this.electric_current_A = data.electric_current_A;
        this.electric_current_B = data.electric_current_B;
        this.electric_current_C = data.electric_current_C;
        this.power_factor_A = data.power_factor_A;
        this.power_factor_B = data.power_factor_B;
        this.power_factor_C = data.power_factor_C;
        this.mv = data.mv;
        
        this.power_factor_summary = data.power_factor_summary;
        this.frequency_network = data.frequency_network;
        this.status_state = data.status_state;
        for(var i = 0; i<=12; i++)
        {
            this[`temperature_num_${i}`] = data[`temperature_num_${i}`];
        }
        for(var i = 1; i<=31; i++)
        {
            this[`special_day_d_${i}`] = data[`special_day_d_${i}`];
            this[`special_day_m_${i}`] = data[`special_day_m_${i}`];
            this[`special_day_t_${i}`] = data[`special_day_t_${i}`];
        }
        this.selected_d_archive = data.selected_d_archive;
        this.selected_date = data.selected_date;
        for(var i = 2; i<=48; i++)
        {
            this[`date_${i}`] = data[`date_${i}`];
        }
        this.half_hour_slices_active_power = data.half_hour_slices_active_power;
        this.temp = data.temp;
        this.journal = data.journal;
        this.number_phase = data.number_phase;
        this.active_power_A = data.active_power_A;
        this.active_power_B = data.active_power_B;
        this.active_power_C = data.active_power_C;
        this.active_power_summary = data.active_power_summary;
        this.reactive_power_A = data.reactive_power_A;
        this.reactive_power_B = data.reactive_power_B;
        this.reactive_power_C = data.reactive_power_C;
        this.reactive_power_summary = data.reactive_power_summary;
        this.total_power_A = data.total_power_A;
        this.total_power_B = data.total_power_B;
        this.total_power_C = data.total_power_C;
        this.total_power_summary = data.total_power_summary;



        
        this.date_1 = data.date_1;
        this.date_2 = data.date_2;
        this.period_avg_1 = data.period_avg_1;
        this.period_avg_2 = data.period_avg_2;
        this.A_p_1 = data.A_p_1;
        this.A_m_1 = data.A_m_1;
        this.R_p_1 = data.R_p_1;
        this.R_m_1 = data.R_m_1;
        this.A_p_2 = data.A_p_2;
        this.A_m_2 = data.A_m_2;
        this.R_p_2 = data.R_p_2;
        this.R_m_2 = data.R_m_2;
        this.UUID = data.UUID;
        this.serial = data.serial;
        this.model = data.model;
        this.count_phase = data.count_phase;
        this.count_rate = data.count_rate;
        this.relay_state = data.relay_state;
        this.release_date = data.release_date;
        this.version_soft = data.version_soft;
        this.kt = data.kt;
        this.data_b = data.data_b;
        this.size_package_in = data.size_package_in;
        this.size_package_out = data.size_package_out;
        this.num_out = data.num_out;
        this.count_package = data.count_package;
        this.B_1 = data.B_1;
        this.B_2 = data.B_2;
        this.B_3 = data.B_3;
        this.A_1 = data.A_1;
        this.A_2 = data.A_2;
        this.A_3 = data.A_3;
        this.P_1 = data.P_1;
        this.P_2 = data.P_2;
        this.P_3 = data.P_3;
        this.Q_1 = data.Q_1;
        this.Q_2 = data.Q_2;
        this.Q_3 = data.Q_3;
        this.S_1 = data.S_1;
        this.S_2 = data.S_2;
        this.S_3 = data.S_3;
        this.address = data.address;
        this.cmd_code = data.cmd_code;
        this.state_energy = data.state_energy;
        this.size_data = data.size_data;
        this.size_data_package = data.size_data_package;
        this.num_package = data.num_package;
        //клеммная крышка
        this.state_1 = data.state_1;
        //корпуса крышка
        this.state_2 = data.state_2;
        //Состояние реле ограничения нагрузки
        this.state_3 = data.state_3;
        this.rssi_sensor = data.rssi_sensor;
        this.data_therm_1 = data.data_therm_1;
        this.data_therm_2 = data.data_therm_2;
        this.data_therm_3 = data.data_therm_3;
        this.data_therm_4 = data.data_therm_4;
        this.data_type = data.data_type;
        this.data_sensor = data.data_sensor;
        this.total_heat_carrier_volume = data.total_heat_carrier_volume;
        this.active_channel_security_1 = data.active_channel_security_1;
        this.active_channel_security_2 = data.active_channel_security_2;
        this.current_coolant_flow      = data.current_coolant_flow;
        this.working_time_h            = data.working_time_h;
    }
    get_time()
    {
        return this.time!==undefined?moment.unix(this.time).format('LLL' ).replace(',','' ):'-';
    }
    get_time_original_2(yy,mm,dd)
    {
        try
        {
            yy = parseInt(yy);
            mm = parseInt(mm);
            dd = parseInt(dd);
            var validYY = typeof yy == 'number' && !isNaN(yy) && yy >= 0 && yy <= 99;
            var validMM = typeof mm == 'number' && !isNaN(mm) && mm >= 1 && mm <= 12;
            var validDD = typeof dd == 'number' && !isNaN(dd) && dd >= 1 && dd <= 31;
            if( validYY && validMM )
            {
                yy = yy + 2000;
                mm--;
                if (!validDD) return moment().utc().year(yy).month(mm).format('MM.YYYY');
                return moment().utc().year(yy).month(mm).date(dd).format('L');
            }
            else
            {
                return '-';
            }
        }
        catch(e)
        {
            return '-';
        }
    }
    get_time_original_range(param)
    {
        if( param === undefined ) return '-';

        var begin_h = moment.unix(param).utc().hour();
        if( begin_h.toString().length === 1) begin_h = '0' + begin_h;
        var begin_m = moment.unix(param).utc().minute();
        if( begin_m.toString().length === 1) begin_m = '0' + begin_m;

        var end_h = moment.unix(param+(60*30)).utc().hour();
        if( end_h.toString().length === 1) end_h = '0' + end_h;
        var end_m = moment.unix(param+(60*30)).utc().minute();
        if( end_m.toString().length === 1) end_m = '0' + end_m;

        return begin_h+':'+begin_m+' - '+end_h+':'+end_m;
    }
    get_time_original_3(param,format)
    {
        if( format === undefined ) format = 'lll';
        if( param === undefined ) return '-';
        return moment.unix(param).utc().format(format).replace(',','' );
    }
    get_time_original(param,format)
    {
        if( format === undefined ) format = 'LLL';
        if( param === undefined ) param = 'time';
        return this[param]!==undefined?moment.unix(this[param]).utc().format(format).replace(',','' ):'-';
    }
    get_ts_original(param,format)
    {
        if( format === undefined ) format = 'LLL';
        if( param === undefined ) param = 'time';
        return this[param]!==undefined?moment(this[param]).utc().format(format).replace(',','' ):'-';
    }
    get_ts()
    {
        return moment(this.ts).format('LLL' ).replace(',','' );
    }
    get_value(init_val,division,kt)
    {
        var my_convert =  new vega_converter();
        var valid = new valid_data();
        kt = valid.isNumber(kt)?kt:1;
        return my_convert.round_size(((init_val*division+this.sensor)/division)*kt,3);
    }
}
class device extends vega_converter
{
    constructor()
    {
        super();
        this.devEui=0;
        this.device_type=0;
        this.version = undefined;
        this.sn = undefined;
        this.count_channels=0;
        this.trans_period=0;
        this.lat=0;
        this.lng=0;
        this.devName="";
        this.last_data_ts="";
        this.last_data_charge=false;
        this.other_info;
        this.channels=new Array();
        this.info = {
            ts:0,
            data:new Object()
        };
        this.diagnostic = {
            ts:0,
            data:new Object()
        };
        this.settings = 
        {
            ts:0,
            params:new Object()
        };
        this.tempSettings = new Object();
    }
    refreshTempSetting()
    {
        var jsonSettings = JSON.stringify(this.settings);
        this.tempSettings = JSON.parse(jsonSettings);        
    }
    getHexTempSettings(channel,settings)
    {
        var resultHex = '00';
        if ( isObject(this.tempSettings.params) )
        {
            for(var i = 0; i < settings.length; i++)
            {
                var id = settings[i];
                var param = this.tempSettings.params[id];
                if (param.id===undefined)
                {
                    param.id = parseInt( id );
                }
                var hexParam = this.encodeParamSettings(param,channel);
                resultHex += hexParam;
            }
        }
        var countBytes = Math.round(resultHex.length/2);
        if ((countBytes)>51)
        {
            return '';
        }
        return resultHex;
    }
    encodeParamSettings(param, channel)
    {
        var paramHex = '';
        var id = param.id;
        var value = param.value;
        var hexValue = '';
        switch ( id ) {
            case 50:
                    var hexValue0 = this.intToHex(value[0],1);
                    var hexValue1 = this.intToHex(value[1],1);
                    var hexValue2 = this.intToHex(value[2],1);
                    hexValue = hexValue0+hexValue1+hexValue2;
                break;
            case 51:
                var hexValue0 = this.intToHex(value[0],1);
                var hexValue1 = this.intToHex(value[1],1);
                var hexValue2 = this.intToHex(value[2],1);
                hexValue = hexValue0+hexValue1+hexValue2;
                break;
            case 52:
                    var hexValue0 = this.intToHex(value[0],1);
                    var hexValue1 = this.intToHex(value[1],1);
                    var hexValue2 = this.intToHex(value[2],1);
                    hexValue = hexValue0+hexValue1+hexValue2;
                break;
            case 54:
                    hexValue = this.uIntToHex(value,4);
                break;
            case 55:
                    hexValue = this.intToHex(value,2);
                break;
            case 80:
                    hexValue = this.intToHex(value,1);
                break;
            case 81:
                    hexValue = this.intToHex(value,1);
                break;
            case 84:
                    hexValue = this.uIntToHex(value,4);
                break;
            case 85:
                    hexValue = this.uIntToHex(value,2);
                break;
            case 86:
                    hexValue = this.uIntToHex(value,2);
                break;
            case 88:
                    hexValue = this.uIntToHex(value);
                break;
            case 89:
                    hexValue = this.uIntToHex(value);
                break;

            case 115:
                    hexValue = this.uIntToHex(value,1);
                break;
            case 116:
                    hexValue = this.uIntToHex(value,1);
                break;
            case 117:
                    hexValue = this.uIntToHex(value,2);
                break;
            case 118:
                    hexValue = this.uIntToHex(value,2);
                break;
            case 119:
                    hexValue = this.uIntToHex(value,2);
                break;
            case 120:
                    hexValue = this.uIntToHex(value,2);
                break;
                
            case 124:
                    hexValue = this.uIntToHex(value,1);
                break;
            case 126:
                    hexValue = this.uIntToHex(value,1);
                break;
            default:
                    hexValue = this.uIntToHex(value);
                break;
        }
        var hexId = this.intToBytes(id,2);
        var size = Math.round(hexValue.length/2);
        var hexSize = this.intToBytes(size,1);
        var validHexSize = hexSize&&hexSize.length%2===0&&size<=255;
        var validHexId = hexId&&hexId.length%2===0&&id<=(256*256-1);
        var validHexValue = hexValue&&hexValue.length%2===0;
        if (validHexSize&&validHexValue&&validHexId)
        {
            paramHex=hexId+hexSize+hexValue;
        }
        return paramHex;
    }
    setSettings(data)
    {
        if (data.ts<=this.settings.ts) 
        {
            return false;
        }
        this.settings.ts = data.ts;
        for(var key in data)
        {
            this.settings[key] = data[key];
        }
        
        var hex = data.data;
        this.settings.bytesList = this.hexToBytes(hex);
        var cloneBytesList = cloneArr(this.settings.bytesList);
        var paramsSettings = this.bytesToParamsSettings(cloneBytesList);
        for(var key in paramsSettings)
        {
            var paramSettings = paramsSettings[key];
            var value = this.parseParamSettings(paramSettings.id,paramSettings.rawData);
            paramSettings.value = value.value;
            paramSettings.name = value.name;
        }
        this.settings.params = paramsSettings;
        return true;
    }
    setInfo(data)
    {
        if (data.ts<=this.info.ts) 
        {
            return false;
        }
        this.info.ts = data.ts;
        var hex = data.data;
        var bytes = this.hexToBytes(hex);
        this.info.hex = hex;
        this.info.bytesList = bytes;
        if( !isObject(this.info.data) ) this.info.data = new Object();
        this.info.data.type = this.bytesToUint([bytes[0]]);
        this.info.data.reason = this.bytesToUint([bytes[1]]);
        this.info.data.code_manufacture = this.bytesAsciiToString(bytes,2,17);
        this.info.data.model_device = this.bytesAsciiToString(bytes,18,33);
        this.info.data.release_date = this.bytesToUint([bytes[37],bytes[36],bytes[35],bytes[34]]);
        this.info.data.version_module_electronic_major = this.bytesToUint([bytes[38]]);
        this.info.data.version_module_electronic_minor = this.bytesToUint([bytes[39]]);
        this.info.data.version_soft_device_major = this.bytesToUint([bytes[40]]);
        this.info.data.version_soft_device_minor = this.bytesToUint([bytes[41]]);
        this.info.data.version_protocol_major = this.bytesToUint([bytes[42]]);
        this.info.data.version_protocol_minor = this.bytesToUint([bytes[43]]);
        this.info.data.charge = this.bytesToUint([bytes[44]]);
        this.info.data.count_package = this.bytesToUint([bytes[48],bytes[47],bytes[46],bytes[45]]);
        return true;
    }
    setDiagnostic(data)
    {
        if (data.ts<=this.diagnostic.ts) 
        {
            return false;
        }
        this.diagnostic.ts = data.ts;
        var hex = data.data;
        var bytes = this.hexToBytes(hex);
        this.diagnostic.hex = hex;
        this.diagnostic.bytesList = bytes;
        if( !isObject(this.diagnostic.data) ) this.diagnostic.data = new Object();
        this.diagnostic.data.count_reboot_power = this.bytesToUint([bytes[0]]);
        this.diagnostic.data.count_reboot_soft = this.bytesToUint([bytes[1]]);
        this.diagnostic.data.count_reboot_sum = this.bytesToUint([bytes[2]]);
        this.diagnostic.data.charge = this.bytesToUint([bytes[3]]);
        this.diagnostic.data.state = this.bytesToUint([bytes[4]]);
        this.diagnostic.data.sp = this.bytesToUint([bytes[5],bytes[6],bytes[7],bytes[8]]);
        this.diagnostic.data.diagnostic_data = bytes.slice(9);
        this.diagnostic.data.diagnostic_data_hex = this.diagnostic.data.diagnostic_data.join('');
        return true;
    }
    getInfo()
    {
        var result = {
            ts:'-',
            reason:'-',
            code_manufacture:'-',
            model_device:'-',
            release_date:'-',
            version_module_electronic:'-',
            version_soft_device:'-',
            version_protocol:'-',
            charge:'-',
            count_package:'-'
        };
        var validInfo = isObject(this.info);
        var validTs = validInfo && typeof this.info.ts === 'number' && this.info.ts>0;
        var validDataInfo = validInfo && isObject(this.info.data);
        if( validInfo && validTs && validDataInfo )
        {
            result.ts = moment(this.info.ts).format('LLL');

            if( this.info.data.reason === 1 ) result.reason = 'По запросу';
            else if ( this.info.data.reason === 0 ) result.reason = 'Регистрация в сети';
            else result.reason = 'Неизвестно';

            if( this.info.data.code_manufacture ) result.code_manufacture = this.info.data.code_manufacture;
            
            if( this.info.data.model_device ) result.model_device = this.info.data.model_device;
            
            var validReleaseDate = typeof this.info.data.release_date === 'number' && this.info.data.release_date > 0;
            if( validReleaseDate ) result.release_date = moment(this.info.data.release_date * 1000).format('LLL');
            
            // var validVME = this.info.data.version_module_electronic && this.info.data.version_module_electronic !== 0xffff;
            // if( validVME ) result.version_module_electronic = this.info.data.version_module_electronic;
            var validVME = typeof this.info.data.version_module_electronic_major === 'number' && typeof this.info.data.version_module_electronic_minor === 'number';
            if( validVME ) result.version_module_electronic = `${this.info.data.version_module_electronic_major}.${this.info.data.version_module_electronic_minor}`;

            var validVSD = typeof this.info.data.version_soft_device_major === 'number' && typeof this.info.data.version_soft_device_minor === 'number';
            if( validVSD ) result.version_soft_device = `${this.info.data.version_soft_device_major}.${this.info.data.version_soft_device_minor}`;

            var validVPM = typeof this.info.data.version_protocol_major === 'number' && typeof this.info.data.version_protocol_minor === 'number';
            if( validVPM ) result.version_protocol = `${this.info.data.version_protocol_major}.${this.info.data.version_protocol_minor}`;
            
            var validCharge = typeof this.info.data.charge === 'number';
            if( validCharge ) result.charge = this.info.data.charge;

            var validCountPackage = typeof this.info.data.count_package === 'number';
            if( validCountPackage ) result.count_package = this.info.data.count_package;
        }
        
        return result;
    }
    getDiagnostic()
    {
        var result = {
            ts:'-',
            count_reboot_power:'-',
            count_reboot_soft:'-',
            count_reboot_sum:'-',
            charge:'-',
            state:'-',
            sp:'-',
            diagnostic_data:'-'
        };

        var validDiagnostic = isObject(this.diagnostic);
        var validTs = validDiagnostic && typeof this.diagnostic.ts === 'number' && this.diagnostic.ts>0;
        var validDataDiagnostic = validDiagnostic && isObject(this.diagnostic.data);
        if( validDiagnostic && validTs && validDataDiagnostic )
        {
            result.ts = moment(this.diagnostic.ts).format('LLL');

            if( this.diagnostic.data.state === 1 ) result.state = 'Активно';
            else if ( this.diagnostic.data.state === 0 ) result.state = 'В спячке';
            else result.state = 'Неизвестно';

            var validCRP = typeof this.diagnostic.data.count_reboot_power === 'number';
            if( validCRP ) result.count_reboot_power = this.diagnostic.data.count_reboot_power;

            var validCRS = typeof this.diagnostic.data.count_reboot_soft === 'number';
            if( validCRS ) result.count_reboot_soft = this.diagnostic.data.count_reboot_soft;

            var validCR = typeof this.diagnostic.data.count_reboot_sum === 'number';
            if( validCR ) result.count_reboot_sum = this.diagnostic.data.count_reboot_sum;

            var validCharge = typeof this.diagnostic.data.charge === 'number';
            if( validCharge ) result.charge = this.diagnostic.data.charge;

            var validSP = typeof this.diagnostic.data.sp === 'number';
            if( validSP ) result.sp = this.diagnostic.data.sp;

            if( this.diagnostic.data.diagnostic_data_hex ) result.diagnostic_data = this.diagnostic.data.diagnostic_data_hex;
        }

        return result;
    }
    parseParamSettings(id,bytes)
    {
        var result = 
        {
            value : undefined,
            name : "unknown"
        }
        if (typeof id === 'number' && isObject(bytes) )
        {
            switch ( id ) 
            {
                case 1:
                    result.name='SETTING_FREQ_PLAN';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 2:
                    result.name='SETTING_CUSTOM_FREQ_PLAN';
                    break;
                case 3:
                    result.name='SETTING_ACTIVATION_TYPE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 4:
                    result.name='SETTING_CONFIRMATION';
                    result.value = this.bytesToUint(bytes);
                    //0 или 1
                    break;
                case 5:
                    result.name='SETTING_ADR';
                    result.value = this.bytesToUint(bytes);
                    //0 или 1
                    break;
                case 6:
                    result.name='SETTING_RX1_DELAY';
                    break;
                case 7:
                    result.name='SETTING_JOIN1_DELAY';
                    break;
                case 8:
                    result.name='SETTING_NB_TRANS';
                    result.value = this.bytesToUint(bytes);
                    //1-15
                    break;
                case 9:
                    result.name='SETTING_TX_POWER';
                    break;
                case 10:
                    result.name='SETTING_DATARATE';
                    break;
                case 11:
                    result.name='SETTING_CHANNEL_MASK';
                    break;
                case 12:
                    result.name='SETTING_INPUT1_MODE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 13:
                    result.name='SETTING_INPUT2_MODE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 14:
                    result.name='SETTING_INPUT3_MODE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 15:
                    result.name='SETTING_INPUT4_MODE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 16:
                    result.name='SETTING_TRANS_PERIOD';
                    result.value = this.bytesToUint(bytes);
                    //1 - 1H
                    //2 - 6H
                    //3 - 12H
                    //4 - 24H
                    //5 - 5m
                    //6 - 15m
                    //7 - 30m
                    break;
                case 17:
                    result.name='SETTING_OUTPUT1_MODE';
                    break;
                case 18:
                    result.name='SETTING_OUTPUT2_MODE';
                    break;
                case 19:
                    result.name='SETTING_PLUGGED_DEVICE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 20:
                    result.name='SETTING_INTERFACE_SPEED';
                    break;
                case 21:
                    result.name='SETTING_INTERFACE_ANS_TIMEOUT';
                    break;
                case 22:
                    result.name='PLUGGED_DEVICE_ADDRESS';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 23:
                    result.name='PLUGGED_DEVICE2_ADDRESS';
                    break;
                case 24:
                    result.name='PLUGGED_DEVICE3_ADDRESS';
                    break;
                case 25:
                    result.name='PLUGGED_DEVICE4_ADDRESS';
                    break;
                case 26:
                    result.name='PLUGGED_DEVICE5_ADDRESS';
                    break;
                case 27:
                    result.name='PLUGGED_DEVICE6_ADDRESS';
                    break;
                case 28:
                    result.name='PLUGGED_DEVICE7_ADDRESS';
                    break;
                case 29:
                    result.name='PLUGGED_DEVICE8_ADDRESS';
                    break;
                case 30:
                    result.name='PLUGGED_DEVICE9_ADDRESS';
                    break;
                case 31:
                    result.name='PLUGGED_DEVICE10_ADDRESS';
                    break;
                case 32:
                    result.name='SETTING_MBUS_INTERFACE_SPEED';
                    break;
                case 33:
                    result.name='SETTING_MBUS_DEVICE_TYPE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 34:
                    result.name='SETTING_INTERFACE_DATABITS';
                    break;
                case 35:
                    result.name='SETTING_INTERFACE_STOPBITS';
                    break;
//                case 36:
//                    result.name='SETTING_INTERFACE_STOPBITS';
//                    break;
                case 37:
                    result.name='SETTING_INTERFACE_PARITY';
                    break;
                case 38:
                    result.name='SETTING_INPUT1_GUARD_MODE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 39:
                    result.name='SETTING_INPUT2_GUARD_MODE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 40:
                    result.name='SETTING_INPUT3_GUARD_MODE';
                    break;
                case 41:
                    result.name='SETTING_INPUT4_GUARD_MODE';
                    break;
                case 42:
                    result.name='SETTING_TEMP_SENSOR_TYPE';
                    break;
                case 43:
                    result.name='SETTING_ALARM_THRESHOLD';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 44:
                    result.name='SETTING_SENSOR_SENSIVITY';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 45:
                    result.name='SETTING_SVE_TRANS_PERIOD';
                    break;
                case 46:
                    result.name='SETTING_SVE_MONTH_DAY';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 47:
                    result.name='SETTING_SVE_WEEK_DAY';
                    break;
                case 48:
                    result.name='SETTING_TP_HEAT_TIME';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 49:
                    result.name='SETTING_COLLECTION_PERIOD';
                    result.value = this.bytesToUint(bytes);
                    //1 - 1H
                    //2 - 6H
                    //3 - 12H
                    //4 - 24H
                    //5 - 5m
                    //6 - 15m
                    //7 - 1m
                    break;
                case 50:
                    result.name='SETTING_ELECTRO_INFO_PACKET_PERIOD';
                    var b1 = this.bytesToUint([bytes[0]]);
                    var b2 = this.bytesToUint([bytes[1]]);
                    var b3 = this.bytesToUint([bytes[2]]);
                    result.value = [b1,b2,b3];
                    break;
                case 51:
                    result.name='SETTING_ELECTRO_INSTANT_PACKET_PERIOD';
                    var b1 = this.bytesToUint([bytes[0]]);
                    var b2 = this.bytesToUint([bytes[1]]);
                    var b3 = this.bytesToUint([bytes[2]]);
                    result.value = [b1,b2,b3];
                    //result.value = this.bytesToUint(bytes);
                    break;
                case 52:
                    result.name='SETTING_ELECTRO_ENERGY_PACKET_PERIOD';
                    var b1 = this.bytesToUint([bytes[0]]);
                    var b2 = this.bytesToUint([bytes[1]]);
                    var b3 = this.bytesToUint([bytes[2]]);
                    result.value = [b1,b2,b3];
                    break;
                case 53:
                    result.name='SETTING_ELECTRO_ENABLE_POWER_PROFILE';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 54:
                    result.name='SETTING_ELECTRO_METER_PASSWORD';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 55:
                    result.name='SETTING_TIMEZONE';
                    result.value = this.bytesToInt(bytes);
                    break;
                case 56:
                    result.name='SETTING_START_READINGS';
                    break;
                case 57:
                    result.name='SETTING_MODIFIED_APPEUI';
                    break;
                case 58:
                    result.name='SETTING_MODIFIED_APPKEY';
                    break;
                case 59:
                    result.name='SETTING_MODIFIED_NWKSKEY';
                    break;
                case 60:
                    result.name='SETTING_MODIFIED_APPSKEY';
                    break;
                case 61:
                    result.name='SETTING_MODIFIED_DEVADDR';
                    break;
                case 62:
                    result.name='SETTING_LM_MOVE_COLLECTION_PERIOD';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 63:
                    result.name='SETTING_LM_MOVE_TRANS_PERIOD';
                    result.value = this.bytesToUint(bytes);
                    //1 - 1H
                    //2 - 6H
                    //3 - 12H
                    //4 - 24H
                    //5 - 5m
                    //6 - 15m
                    //7 - 30m
                    break;
                case 64:
                    result.name='SETTING_GSM_TX_TECHNOLOGY';
                    break;
                case 65:
                    result.name='SETTING_GSM_NETWORK_MODE';
                    break;
                case 66:
                    result.name='SETTING_GSM_HOST_IP';
                    break;
                case 67:
                    result.name='SETTING_GSM_HOST_PORT';
                    break;
                case 68:
                    result.name='SETTING_GSM_TOPIC_NAME';
                    break;
                case 69:
                    result.name='SETTING_GSM_CLIENT_ID';
                    break;
                case 70:
                    result.name='SETTING_GAS_DECIMAL_COUNT';
                    break;
                case 71:
                    result.name='SETTING_LM_MOVE_ALARM';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 72:
                    result.name='SETTING_ELECTRO_ENABLE_SEND_EVENTS';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 73:
                    result.name='SETTING_GNSS_MODULE';
                    break;
                case 74:
                    result.name='SETTING_GSM_CONNECT_APN';
                    break;
                case 75:
                    result.name='SETTING_GSM_CONNECT_USERNAME';
                    break;
                case 76:
                    result.name='SETTING_GSM_CONNECT_PASSWORD';
                    break;
                case 77:
                    result.name='SETTING_GSM_CONNECT_PROTOCOL';
                    break;
                case 78:
                    result.name='SETTING_ALARM_COLLECTION_PERIOD';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 79:
                    result.name='SETTING_INSTANT_SEND';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 80:
                    result.name='SETTING_TEMPERATURE_LIMIT_LOW';
                    result.value = this.bytesToInt(bytes);
                    break;
                case 81:
                    result.name='SETTING_TEMPERATURE_LIMIT_HIGH';
                    result.value = this.bytesToInt(bytes);
                    break;
                case 82:
                    result.name='SETTING_SMOKE_THRESHOLD';
                    break;
                case 83:
                    result.name='SETTING_LIMIT_ENERGY';
                    break;
                case 84:
                    result.name='SETTING_LIMIT_POWER';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 85:
                    result.name='SETTING_LIMIT_LOW';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 86:
                    result.name='SETTING_LIMIT_HIGH';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 88:
                    result.name='SETTING_HUMID_LIMIT_LOW';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 89:
                    result.name='SETTING_HUMID_LIMIT_HIGH';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 114:
                    result.name='SETTING_ELECTRO_TRANS_PERIOD';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 115:
                    result.name='SETTING_NOISE_THRESHOLD_LOW';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 116:
                    result.name='SETTING_NOISE_THRESHOLD_HI';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 117:
                    result.name='SETTING_LIGHT_THRESHOLD_LOW';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 118:
                    result.name='SETTING_LIGHT_THRESHOLD_HI';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 119:
                    result.name='SETTING_CO2_THRESHOLD_LOW';
                    result.value = this.bytesToUint(bytes);
                    break;
                case 120:
                    result.name='SETTING_CO2_THRESHOLD_HI';
                    result.value = this.bytesToUint(bytes);
                    break;

                case 124:
                    result.name='SETTING_AUTOARMING_MESSAGE_ENABLE';
                    result.value = this.bytesToInt(bytes);
                    break;
                case 126:
                    result.name='SETTING_TRANS_PERIOD_BY_DAY';
                    result.value = this.bytesToUint(bytes);
                    break;
                default:
                    break;
            }
        }
        
        return result;
    }
    valid(str)
    {
       return str&&str!=undefined&&str.toString().length>0?true:false;
    }
    set_device(obj,deviceType)
    {   
        var count_channels = undefined;
        if( isObject(deviceType) )
        {
            count_channels = deviceType.count_channels;
            this.device_type=obj.device_type;
            this.version=obj.version;
            this.sn=obj.sn;
            
            if( this.version === undefined && isObject(deviceType.versions) )
            {
                this.version = deviceType.versions.first;
            }
        }
        if (this.valid(obj.devEui))
        {
            this.devEui=obj.devEui;
        }
        else
        {
            return false;
        }
        if (count_channels!=undefined&&count_channels>0)
        {
            if (count_channels>50)
            {
                count_channels=50;
            }
            for (var i =0;i<count_channels;i++)
            {
                if (obj['other_info_'+(i+1)]&&obj['other_info_'+(i+1)]!=undefined)
                {
                    var mychanneel_obj = {};
                    try
                    {
                        if(typeof obj['other_info_'+(i+1)] === 'object' )
                        {
                            mychanneel_obj = obj['other_info_'+(i+1)];
                        }
                        else if(typeof obj['other_info_'+(i+1)] === 'string')
                        {   
                            mychanneel_obj = JSON.parse(obj['other_info_'+(i+1)])
                        }
                        this.channels[i] = mychanneel_obj;
                        this.channels[i].history = new Array();
                        this.channels[i].statistics=new Statistic();
                    }
                    catch(err)
                    {
                         this.channels[i]=obj['other_info_'+(i+1)];
                         this.channels[i].history = new Array();
                         this.channels[i].statistics=new Statistic();
                    }
                }
                else
                {
                    this.channels[i]=new Object();
                    this.channels[i].history = new Array();
                    this.channels[i].statistics=new Statistic();
                    this.channels[i].num_channel=i+1;
                }
                this.channels[i]._self = this;
                this.channels[i].edit=new Channel().edit;
                this.channels[i].getInfo=new Channel().getInfo;
                this.channels[i].devEui = this.devEui;
                this.channels[i].last_data_charge = this.last_data_charge;
            }
        }
        if (this.valid(obj.trans_period))
        {
            this.trans_period=obj.trans_period;
        }
        if (obj.last_data_ts!=undefined&&obj.last_data_ts>0&&obj.last_data_ts.toString().length<=13)
        {
            this.last_data_ts=obj.last_data_ts;
        }
        if (this.valid(obj.devName))
        {
            this.devName=obj.devName;
        }
        if (this.valid(obj.lat))
        {
            this.lat=obj.lat;
        }
        if (this.valid(obj.lng))
        {
            this.lng=obj.lng;
        }
        if (this.valid(obj.other_info))
        {
            try{
                this.other_info=JSON.parse(obj.other_info);
            }
            catch(err)
            {
                
            }
        }
        return this;
    }
    get_json()
    {
        try
        {
            return JSON.stringify(this);
        }
        catch(err)
        {
            return false;
        }
    }
}
class audioControl 
{
    constructor(tag,status)
    {
        this.audio = document.getElementsByTagName(tag)[0];
        this.audio.status = status;
    }
    play()
    {
        if( !this.valid() ) return false;
        this.audio.play().catch(function() {
            console.log('play audio error');
        });
    }
    pause()
    {
        if( !this.valid() ) return false;
        this.audio.pause();
    }
    currentTime(time)
    {
        if( !this.valid() ) return false;
        if( time === undefined ) time = 0;
        this.audio.currentTime = time;
    }
    stop()
    {
        if( !this.valid() ) return false;
        this.pause();
        this.currentTime();
    }
    replayAudio()
    {
        if( !this.valid() ) return false;
        this.stop();
        this.play();
    }
    toggleMutedAudio()
    {
        if( !this.valid() ) return false;
        if( this.audio.muted ) this.audio.muted = false;
        this.audio.muted = true;
    }
    valid()
    {
        return isObject(this.audio) && this.audio.status ;
    }
}
class map_nav extends audioControl
{
    constructor(tagAudio,stateAudio)
    {
        super(tagAudio,stateAudio);
        this.level_1_list = new Array();
        this.level_2_list = new Array();
        this.level_2_filter_list = new Array();
        this.level_3_list = new Array();
        this.check_level_1=-1;//Выбранный объект
        this.check_level_2=-1;//Выбранное помещение
        this.history_danger = new Array();
        this.check_level_1_arr = [];
        this.check_level_2_arr = [];
        this.list = new Object();
        this.filterDevices = '';
        this.filter = new Object();
    }
    select(nameL1,addressL1,level2)
    {
        if(!nameL1||!addressL1) return
        var hashL1 = md5(nameL1+addressL1);
        var l1 = this.list[hashL1];
        var validL1 = typeof l1 === 'object' && typeof l1.list === 'object';
        if(!validL1) return;
        l1._check = true;
        if(!level2) return;
        var hashL2 = md5(level2);
        var l2 = l1.list[hashL2];
        var validL2 = typeof l1 === 'object' && typeof l1.list === 'object';
        if(!validL2) return;
        l2._check = true;
        return true;
    }
    checkFilter()
    {
        for(var key in this.filter)
        {
            if(this.filter[key])
            {
                return true;
            }
        }
        return false;
    }
    //запись в массив истории тут,  и функции поиска по лев 1 лев2  и тд 
    set_history_danger(devEui,num,name_level_1,address_level_1,level_2)
    {
        var tempObj = new Object();
        tempObj.devEui = devEui;
        tempObj.num = num;
        tempObj.name_level_1 = name_level_1;
        tempObj.address_level_1 = address_level_1;
        tempObj.level_2 = level_2;
        this.history_danger.push(tempObj);
        this.replayAudio();
    }
    get_level_1_danger(name_level_1,address_level_1)
    {
        var countDanger = 0;
        for (var i=0;i< this.history_danger.length;i++)
        {
            if (this.history_danger[i].name_level_1==name_level_1&&this.history_danger[i].address_level_1==address_level_1)
            {
                countDanger++;
            }
        }
        return countDanger;
    }
    get_level_2_danger(level_2,name_level_1,address_level_1)
    {
        var countDanger = 0;
        for (var i=0;i< this.history_danger.length;i++)
        {
            if (this.history_danger[i].level_2==level_2&&this.history_danger[i].name_level_1==name_level_1&&this.history_danger[i].address_level_1==address_level_1)
            {
                countDanger++;
            }
        }
        return countDanger;
    }
    checkSelectedLevel_1(level_1)
    {
        var validLevel_1 = level_1!==undefined&&level_1.name!==undefined&&level_1.address!==undefined;
        if (validLevel_1)
        {
            var key = level_1.name.toString()+level_1.address.toString();
            var chackLevelSelected = this.check_level_1_arr[key]!==undefined;
            if (chackLevelSelected)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
     checkSelectedLevel_2(level_2)
    {
        var validLevel_2 = level_2!==undefined;
        if (validLevel_2)
        {
            var key = level_2.name.toString();
            var chackLevelSelected = this.check_level_2_arr[key]!==undefined;
            if (chackLevelSelected)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    select_check_level_2(level_2)
    {
        var validLevel_2 = level_2!==undefined;
        if (validLevel_2)
        {
            var key = level_2.name.toString();
            var chackLevelSelected = this.check_level_2_arr[key]!==undefined;
            if (chackLevelSelected)
            {
                delete this.check_level_2_arr[key];
            }
            else
            {
                this.check_level_2_arr[key] = level_2;
            }
        }
    }
    set_danger_level_1()
    {
        
    }
    level_2_list_f(level_1)
    {
        var res = [];
        var validL1 = level_1&& isObject(level_1) &&level_1.name_level_1!==undefined&&level_1.address_level_1!==undefined;
        if (validL1)
        {
            var nameL1 = level_1.name_level_1;
            var addressL1 = level_1.address_level_1;
            var hashL1 = md5(nameL1+addressL1);
            var l1 = this.list[hashL1];
            if ( l1 && isObject(l1) && l1.list && isObject(l1.list) )
            {
                for (var key in l1.list)
                {
                    var l2 = l1.list[key];
                    if ( l2 && isObject(l2) && l2.name )
                    {
                        res.push(l2.name);
                    }
                }
                return res;
            }
        }
        return this.level_2_list;
    }
    add(channel)
    {
        if (channel)
        {
            var nameL1 = channel.name_level_1;
            var addressL1 = channel.address_level_1;
            var nameL2 = channel.level_2;
            var nameL3 = channel.name;
            if (!nameL1||!addressL1||!nameL2||!nameL3) return;
            var hashL1 = md5(nameL1+addressL1);
            var hashL2 = md5(nameL2);
            var hashL3 = md5(nameL3+channel.num_channel+channel.devEui);
            if (!this.list[hashL1])
            {
                this.set_level_1(nameL1,addressL1);
                var self = this;
                this.list[hashL1] = {
                    name:nameL1,
                    address:addressL1,
                    self:self,
                    check:function(){
                       this._check=!this._check;
                    },
                    list:new Object(),
                    getChannels: function(param,value){
                        var result = new Object();
                        var dublicates = [];
                        for(var key in this.list)
                        {
                            var l2 = this.list[key];
                            if (l2.list)
                            {
                               for(var key2 in l2.list)
                               { 
                                   
                                   var channel = l2.list[key2];
                                   var uniqKey = key+key2;
                                   channel.uniqKey = uniqKey;
                                   var hk = channel.$$hashKey.split(':' )[1];
                                   if (channel[param] == value && !dublicates[hk] )
                                   {
                                       dublicates[hk]=true
                                       result[uniqKey] = channel;
                                   }
                               }
                            }
                        }
                        return result;
                    },
                    checkPresenceTypeChannel: function(type){
                        for(var key in this.list)
                        {
                            var l2 = this.list[key];
                            if (l2.list)
                            {
                               for(var key in l2.list)
                               { 
                                   var channel = l2.list[key];
                                   if (channel.type_channel == type)
                                   {
                                       return true;
                                   }
                               }
                            }
                        }
                        return false;
                    },
                    valid: function(){
                        if (this.list)
                        {
                            for(var key in this.list)
                            {
                                var l2 = this.list[key];
                                if (l2.list)
                                {
                                   for(var key in l2.list)
                                   { 
                                       var channel = l2.list[key];
                                       if (channel.name&&this.name==channel.name_level_1&&this.address==channel.address_level_1&&channel.level_2==l2.name) 
                                       {
                                           var filter = this.self.filterDevices;
                                           var fullFilter = this.self.filter;
                                           var checkFullFilter = this.self.checkFilter();
                                           if (filter||checkFullFilter)
                                           {
                                               filter = filter.toLowerCase();
                                               var name_lavel_1 = this.name.toLowerCase();
                                               var address_lavel_1 = this.address.toLowerCase();
                                               var validlevel1 = name_lavel_1.indexOf(filter)>-1||address_lavel_1.indexOf(filter)>-1;
                                               if (!checkFullFilter&&validlevel1) return true;
                                               for(var keyLevel2 in this.list)
                                               {
                                                   var l2 = this.list[keyLevel2];
                                                   var validLevel2 = l2.name&&l2.name.toLowerCase().indexOf(filter)>-1;
                                                   if (!checkFullFilter&&validLevel2) return true;
                                                   for(var keyChannel in l2.list)
                                                   {
                                                       var thischannel = l2.list[keyChannel];
                                                       var nameChannel = thischannel.name;
                                                       var devEuiChannel = thischannel.devEui;
                                                       var validNameChannel = typeof nameChannel === 'string';
                                                       var validDeviceModel = thischannel._self.device_type == fullFilter.deviceModel || fullFilter.deviceModel == undefined || fullFilter.deviceModel == 0;
                                                       if (validNameChannel&&nameChannel) nameChannel=nameChannel.toLowerCase();
                                                       if (devEuiChannel) devEuiChannel=devEuiChannel.toLowerCase();
                                                       var validChannel = validNameChannel&&(nameChannel.indexOf(filter)>-1||devEuiChannel.indexOf(filter)>-1);
                                                       if(checkFullFilter&&validDeviceModel)
                                                       {
                                                            if(filter)
                                                            {
                                                                if(validlevel1||validLevel2||validChannel) return true;
                                                                return false;
                                                            }
                                                            return true;
                                                       }
                                                       else if(!checkFullFilter)
                                                       {
                                                        if (validNameChannel&&(nameChannel.indexOf(filter)>-1||devEuiChannel.indexOf(filter)>-1)) return true;
                                                       }
                                                   }
                                               }
                                               return false;
                                           }
                                           return true;
                                       }   
                                   }
                                }
                            }
                        }
                        return false;
                    }
                };
            }
            var level_1 = this.list[hashL1];
            if (!level_1.list[hashL2])
            {
                level_1.list[hashL2] = {
                    name:nameL2,
                    list:new Object(),
                    check:function(){
                       this._check=!this._check;
                    },
                    valid: function(){
                        if (this.list)
                        {
                            for(var key in this.list)
                            { 
                                var channel = this.list[key];
                                if (channel.name&&this.self.name==channel.name_level_1&&this.self.address==channel.address_level_1&&channel.level_2==this.name) 
                                {
                                    var filter = this.self.self.filterDevices;
                                    var fullFilter = this.self.self.filter;
                                    var checkFullFilter = this.self.self.checkFilter();
                                    if (filter||checkFullFilter)
                                    {
                                        filter = filter.toLowerCase();
                                        
                                        var name_lavel_1 = this.self.name.toLowerCase();
                                        var address_lavel_1 = this.self.address.toLowerCase();
                                        var validlevel1 = name_lavel_1.indexOf(filter)>-1||address_lavel_1.indexOf(filter)>-1;
                                        if (!checkFullFilter&&validlevel1) return true;
                                        var l2 = this;
                                        var validLevel2 = l2.name&&l2.name.toLowerCase().indexOf(filter)>-1;
                                        if (!checkFullFilter&&validLevel2) return true;
                                        for(var keyChannel in l2.list)
                                        {
                                            var thischannel = l2.list[keyChannel];
                                            var nameChannel = thischannel.name;
                                            var devEuiChannel = thischannel.devEui;
                                            var validDeviceModel = thischannel._self.device_type == fullFilter.deviceModel || fullFilter.deviceModel == undefined || fullFilter.deviceModel == 0;
                                            if (nameChannel&&devEuiChannel) 
                                            {
                                                nameChannel=nameChannel.toLowerCase();
                                                devEuiChannel=devEuiChannel.toLowerCase();
                                                var validChannel = nameChannel.indexOf(filter)>-1||devEuiChannel.indexOf(filter)>-1;
                                                if(checkFullFilter&&validDeviceModel)
                                                {
                                                    if(filter)
                                                    {
                                                        if(validlevel1||validLevel2||validChannel) return true;
                                                        return false;
                                                    }
                                                    return true;
                                                }
                                                else if(!checkFullFilter)
                                                {
                                                    if (nameChannel.indexOf(filter)>-1||devEuiChannel.indexOf(filter)>-1&&validDeviceModel) return true;
                                                }
                                                
                                            }
                                        }
                                        return false;
                                    }
                                    return true;
                                }
                            }
                        }
                        return false;
                    }
                };
                level_1.list[hashL2].self = level_1;
            }
            this.set_level_2(nameL2);
            var level_2 = level_1.list[hashL2];
            level_2.list[hashL3] = channel;           
            this.set_level_3(channel.name);
        }
    }
    getCountL1()
    {
        return Object.keys(this.list).length;
    }
    getCountL2()
    {
        var tmp = new Object();
        for(var key in this.list)
        {
            var l1 = this.list[key];
            if ( l1 && isObject(l1) )
            {
                for(var hash in l1.list)
                {
                    tmp[hash] = true;
                }
            }
        }
        return Object.keys(tmp).length;
    }
    set_level_1(name,address)
    {
        if (name&&name!=undefined&&address&&address!=undefined)
        {
            var temp = new Object();
            temp.name_level_1=name;
            temp.address_level_1=address;
            temp.danger=false;
            for (var i=0;i<this.level_1_list.length;i++)
            {
                if (this.level_1_list[i].name_level_1==name&&this.level_1_list[i].address_level_1==address)
                {
                    return false;
                }
            }
            this.level_1_list.push(temp);
            return true;
        }
    }
    set_level_2(name)
    {
        if (name!=undefined&&name&&this.level_2_list.indexOf(name.toString())==-1)
        {
            this.level_2_list.push(name.toString());
            this.level_2_filter_list.push({name:name.toString(),tick:true});
        }
    }
    set_level_3(name)
    {
        if (name!=undefined&&name&&this.level_3_list.indexOf(name.toString())==-1)
        {
            this.level_3_list.push(name.toString());
        }
    }
}


